You can use the v-on directive to bind and listen to DOM events. The content of the binding can be a method on the current instance (no parentheses are needed after it) or an inline expression. If a method is provided, the native DOM event will be passed in as the first parameter, and this event will have the targetVM attribute, pointing to the corresponding ViewModel that triggered the event:
<div id="demo"> <a v-on="click: onClick">触发一个方法函数</a> <a v-on="click: n++">触发一个表达式</a> </div>
new Vue({ el: '#demo', data: { n: 0 }, methods: { onClick: function (e) { console.log(e.targetVM.n); console.log(e.target.tagName);// "A" console.log(e.targetVM === this);// true } } });
Execute the expression
targetVM is useful when using v-on in v-repeat, because v-repeat will create a large number of child ViewModels. However, it is more convenient and intuitive to pass in the alias representing the current ViewModel data object by executing the expression:
<ul id="list"> <li v-repeat="item in items" v-on="click: toggle(item)"> {{item.text}} </li> <button v-on="click: submit('hello!', $event)">Submit</button> </ul>
new Vue({ el: '#list', data: { items: [ { text: 'one', done: true }, { text: 'two', done: false } ] }, methods: { toggle: function (item) { console.info(item.done); item.done = !item.done; console.info(item.done); }, submit: function (msg, e) { e.stopPropagation(); console.info(msg + ' submit is called!'); } } })
When you want to access the original DOM event in the expression, you can pass an $event parameter Go in.
key filter
When listening for keyboard events, we often need to determine commonly used key codes. Vue.js provides a special filter that can only be used with the v-on directive: key. It receives a parameter representing the key code and completes the judgment:
<!-- 只有当 keyCode 等于 13 时才调用方法 --> <input v-on="keyup:mySubmit | key 13">
The system has many preset values that can be used, for example:
<!-- 效果同上 --> <input v-on="keyup:submit | key 'enter'">
The default value is: enter tab delete esc up down left right space
Why is it used in HTML Listener
You may notice that the whole way of event listening goes against the traditional concept of "separation of concern". Don't worry, since 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 more benefits:
It makes it easy to locate the corresponding method implementation in JS code in the HTML template.
Because you don’t need to manually bind events in JS, your ViewModel code can be very pure logic, completely decoupled from the DOM. This will be easier to test.
When a ViewModel is destroyed, all event listeners will be automatically removed. You don’t have to worry about cleaning them yourself.
The above is the entire content of this article, I hope it will be helpful to everyone’s study