event handling
Directory
- ##Why listen for events in HTML?
You can use
v- The ondirective listens for DOM events and runs some JavaScript code when triggered.
Example:
<div id="example-1"> <button v-on:click="counter += 1">Add 1</button> <p>The button above has been clicked {{ counter }} times.</p> </div>
var example1 = new Vue({ el: '#example-1', data: { counter: 0 } })Result:
#Event handling method
#However, many event processing logic will be more complex, so it is not feasible to write JavaScript code directly in the v-on
directive. Thereforev-on
can also receive a method name that needs to be called. Example:
<div id="example-2"> <!-- `greet` 是在下面定义的方法名 --> <button v-on:click="greet">Greet</button> </div>
var example2 = new Vue({ el: '#example-2', data: { name: 'Vue.js' }, // 在 `methods` 对象中定义方法 methods: { greet: function (event) { // `this` 在方法里指向当前 Vue 实例 alert('Hello ' + this.name + '!') // `event` 是原生 DOM 事件 if (event) { alert(event.target.tagName) } } } }) // 也可以用 JavaScript 直接调用方法 example2.greet() // => 'Hello Vue.js!'
Result:
## Methods in inline processors
In addition to being directly bound to a method, methods can also be called in inline JavaScript statements: <div id="example-3">
<button v-on:click="say('hi')">Say hi</button>
<button v-on:click="say('what')">Say what</button>
</div>
new Vue({
el: '#example-3',
methods: {
say: function (message) {
alert(message)
}
}
})
Result:
Sometimes it is also necessary to access raw DOM events in the inline statement handler. You can use the special variable
$event to pass it into the method:
<button v-on:click="warn('Form cannot be submitted yet.', $event)"> Submit </button>
// ... methods: { warn: function (message, event) { // 现在我们可以访问原生事件对象 if (event) event.preventDefault() alert(message) } }
Event modifier
It is a very common requirement to call event.preventDefault() or
event.stopPropagation()in an event handler. Although we can easily implement this in methods, it is better to have methods with pure data logic instead of dealing with DOM event details.
To solve this problem, Vue.js provides event modifier
for v-on. As mentioned before, modifiers are represented by instruction suffixes starting with a dot.
.stop
##.prevent
.capture
.self
.once
.passive
##<!-- 阻止单击事件继续传播 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 --> <form v-on:submit.prevent="onSubmit"></form> <!-- 修饰符可以串联 --> <a v-on:click.stop.prevent="doThat"></a> <!-- 只有修饰符 --> <form v-on:submit.prevent></form> <!-- 添加事件监听器时使用事件捕获模式 --> <!-- 即元素自身触发的事件先在此处理,然后才交由内部元素进行处理 --> <div v-on:click.capture="doThis">...</div> <!-- 只当在 event.target 是当前元素自身时触发处理函数 --> <!-- 即事件不是从内部元素触发的 --> <div v-on:click.self="doThat">...</div>
v-on:click.prevent.self2.1.4 Newly addedwill prevent
all clicks
, while v-on:click.self.prevent will only prevent the Click on the element itself.
.once<!-- 点击事件将只会触发一次 --> <a v-on:click.once="doThis"></a>Unlike other modifiers that can only work on native DOM events,
Modifiers can also be used on custom component events
. If you haven't read the documentation on your components, don't worry now.
Vue also corresponds to thepassive
option provided in addEventListener
.passive modifier.
This <!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成 -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
modifier can especially improve mobile performance.
.passivewith
.prevent
because.prevent
will be ignored and the browser may Show you a warning. Remember,.passive
tells the browser that you don't want to block the default behavior of the event.
When listening for keyboard events, we often Need to check detailed keys. Vue allows
v-onto add key modifiers when listening to keyboard events:
<!-- 只有在 `key` 是 `Enter` 时调用 `vm.submit()` --> <input v-on:keyup.enter="submit">
You can directly expose
KeyboardEvent.key is equal to PageDown.
keyCode
event usagefeature is also allowed:has been deprecated
keyCodeand may not be supported by the latest browsers.
Using the
<input v-on:keyup.13="submit">
In order to support old browsers where necessary, Vue provides most commonly used keycodes Alias:
.enter
.tab
.delete
(Captures "Delete" and "Backspace" keys).esc
.space
.up
##.down
.left
.right
Some keys (You can also customize the key modifier alias.esc
and all arrow keys) have different
keyvalues in IE9, if you want to support IE9, these built-in aliases should be preferred .
through the global config.keyCodes
object:
// 可以使用 `v-on:keyup.f1` Vue.config.keyCodes.f1 = 112
System Modifier Key
2.1.0 NewYou can use the following modifiers to Implement a listener for mouse or keyboard events that only fires when the corresponding key is pressed.
.ctrl
- ##.alt
- .shift
- .meta
Note: On a Mac system keyboard, meta corresponds to the command key (?). On the Windows system keyboard meta corresponds to the Windows logo key (?). On Sun operating system keyboards, meta corresponds to the solid gem key (◆). On certain other keyboards, especially those of the MIT and Lisp machines, and their successors, such as the Knight keyboard and the space-cadet keyboard, meta is marked as "META". On the Symbolics keyboard, meta is marked as "META" or "Meta".For example:
<!-- Alt + C --> <input @keyup.alt.67="clear"> <!-- Ctrl + Click --> <div @click.ctrl="doSomething">Do something</div>Please note that modifier keys are different from regular keys. When used together with the
keyupevent, the modifier key is modified when the event is triggered. The key must be pressed. In other words,
keyup.ctrl
can only be triggered by releasing other keys while holding downctrl
. And simply releasingctrl
will not trigger the event. If you want this behavior, usekeyCode
forctrl
instead:keyup.17
.
##.exact Modifier
2.5.0 New
.exactmodifiers allow you to control events triggered by an exact combination of system modifiers.
<!-- 即使 Alt 或 Shift 被一同按下时也会触发 --> <button @click.ctrl="onClick">A</button> <!-- 有且只有 Ctrl 被按下的时候才触发 --> <button @click.ctrl.exact="onCtrlClick">A</button> <!-- 没有任何系统修饰符被按下的时候才触发 --> <button @click.exact="onClick">A</button>
.left
.right
.middle
These Modifiers restrict the handler function to respond only to specific mouse buttons.
Why listen for events in HTML?
You may notice this kind of event The listening approach goes against the longstanding tradition of separation of concerns. But don’t worry, because all Vue.js event handlers and expressions are strictly bound to the current view’s ViewModel, it won’t cause any maintenance difficulties. In fact, using v-on
has several advantages:
1. You can easily locate the corresponding method in the JavaScript code by scanning the HTML template.
2. Because you don’t need to manually bind events in JavaScript, your ViewModel code can be very pure logic, completely decoupled from the DOM, and easier to test.
3. When a ViewModel is destroyed, all event handlers will be automatically deleted. You don’t have to worry about cleaning them.