看到同事写的代码,「@submit.native.prevent」一下子抓不到含义,发现 Vue 在 2.0 以后添加了一些「事件(Event)」方面的功能,学习一下,以作备忘
真相:
.native 表示对一个组件绑定系统原生事件
.prevent 表示提交以后不刷新页面
注册
<button v-on:click="greet">Greet</button> // greet 是 greet() 的简写
<button v-on:click="say('hi')">Say hi</button>
<button v-on:click="warn($event)"> // original DOM event
<button @click="greet"> // for short
事件修正符
<!-- the click event's propagation will be stopped(组织传播) -->
<a v-on:click.stop="doThis"></a>
<!-- the submit event will no longer reload the page(不刷新页面) -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- modifiers can be chained(构建链路) -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- just the modifier(省略事件名) -->
<form v-on:submit.prevent></form>
<!-- use capture mode when adding the event listener(捕获给内部使用) -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>
<!-- only trigger handler if event.target is the element itself(只对自己有效) -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>
<!-- the click event will be triggered at most once(单次有效) -->
<a v-on:click.once="doThis"></a>
按键修正符
按键修正符支持方便的扩展和自定义,默认的有:
.enter(键盘)
.tab
.delete (captures both “Delete” and “Backspace” keys)
.esc
.space
.up
.down
.left
.right
.ctrl(快捷键)
.alt
.shift
.meta
.left(鼠标)
.right
.middle
.native - listen for a native event on the root element of component.
.passive - (2.3.0+) attaches a DOM event with { passive: true }
除了以上几个以外,所有定义在 JavaScript 中的 KeyboardEvent.key 都可以被直接使用(转换为 kebab-case 格式)
<!-- same as above -->
<input v-on:keyup.enter="submit">
<!-- case from KeyboardEvent.key -->
<input @keyup.page-down="onPageDown">
<!-- Alt + C -->
<input @keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
<!-- this will fire even if Alt or Shift is also pressed(也许不是你需要的效果) -->
<button @click.ctrl="onClick">A</button>
<!-- this will only fire when only Ctrl is pressed(.exact 可以帮你解决) -->
<button @click.ctrl.exact="onCtrlClick">A</button>
(在组件上)自定义事件
Listen to an event using
$on(eventName)
Trigger an event using$emit(eventName)
($emit 也可以从子组件中触发父组件中注册的事件)
<el-dialog @close="close">
</el-dialog>
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
绑定系统原生事件的时候,需要加 .native
修正符
<my-component v-on:click.native="doTheThing"></my-component>
疑问
.passive 这个修正符的意思我没有 get 到:
A seemingly minor, but incredibly welcome change in the latest Vue release is the addition of the .passive event modifier to v-on. This allows an event to be bound in such a way that it explicitly says that it won’t cancel the event. This translates to a significant performance improvement on mobile for certain events, such as wheel, touchstart, and touchmove.
We’ll be covering the passive event modifier in JavaScript in the next few days.