In Vue's front-end development, event monitoring is an indispensable function. This article briefly describes the simple usage of v-on through simple small examples, which is for learning and sharing purposes only. If there are any shortcomings, please correct them.
Listen to events
You can listen for DOM events with the v-on directive and run some JavaScript code when triggered. As shown below:
<button v-on:click="counter += 1">Add 1</button> <p>The button was clicked {{ counter }} Second-rate.</p>
where counter is a property value that is customized by Vue.
Event handling method
In fact, many event processing logics are more complex, so it is not feasible to write JavaScript code directly in v-on instructions. Therefore v-on can also receive a method name that needs to be called. As shown below:
<button v-on:click="greet">Greet</button>
greet is the method name defined below. As shown below:
<script type="text/javascript"> var app=new Vue({ el:'#app', data:{ msg:'hello world!!!', counter:0, name: '' }, // Define methods in the `methods` object methods:{ greet: function (event) { // `this` points to the current Vue instance in the method alert('Hello ' + + '!') // `event` is a native DOM event if (event) { alert() } }, } }); </script>
Methods in inline processors
In addition to directly binding to a method, you can also call methods in inline JavaScript statements, as shown below:
<button v-on:click="say('hi')">Say hi</button> <button v-on:click="say('what')">Say what</button>
Sometimes it is also necessary to access the original DOM event in the inline statement processor. You can use the special variable $event to pass it into the method:
<button v-on:click="warn('Forms cannot be submitted.', $event)">submit</button>
where says and warn are custom methods, as shown below:
say: function (message) { alert(message); }, warn: function (message, event) { // Now we can access the native event object if (event) { (); } alert(message); }
Event modifier
Calling () or () in an event handler is a very common requirement. Although we can easily achieve this in methods, a better way is: the method has only pure data logic, rather than dealing with DOM event details. To solve this problem, event modifiers are provided for v-on. As mentioned earlier, the modifier is represented by the suffix of the instruction starting with a dot. The event modifiers are as follows:
- .stop
- .prevent
- .capture
- .self
- .once
- .passive
<!-- Prevent click events from continuing to spread --> <a v-on:="doThis">Click666</a> <!-- Submit event no longer reloads the page --> <form v-on:="onSubmit"> <div>Block submission</div> </form> <!-- Modifiers can be concatenated --> <a v-on:="doThat"></a> <!-- Only modifiers --> <form v-on:> <div >Only modifiers</div> </form> <!-- Use event capture mode when adding event listeners --> <!-- That is, events triggered by internal elements are processed here first,Then it is handed over to the internal element for processing --> <div v-on:="doThis">doThis...</div> <!-- Just as The processing function is triggered when the current element itself --> <!-- That is, events are not triggered from internal elements --> <div v-on:="doThat">doThat...</div>
When using modifiers, the order is important; the corresponding code will be generated in the same order. Therefore, using v-on: will block all clicks, and v-on: will only block clicks on the element itself.
Added attributes
Unlike other modifiers that can only work on native DOM events, the .once modifier can also be used on custom component events.
<!-- Click event will only trigger once --> <a v-on:="doThis">Click me once666</a>
Vue also provides a .passive modifier for the passive option in addEventListener.
<!-- Default behavior of scrolling events (That is, scrolling behavior) Will trigger immediately --> <!-- And won't wait `onScroll` Finish --> <!-- This includes `()` The situation --> <div v-on:="onScroll">...</div>
This .passive modifier can especially improve the performance of the mobile side. Don't use .passive and .prevent together, because .prevent will be ignored, and the browser may show you a warning. Remember that .passive will tell the browser the default behavior you don't want to block events.
Key modifier
When listening to keyboard events, we often need to check detailed keys. Vue allows adding key modifiers for v-on when listening for keyboard events:
<!-- Only in `key` yes `Enter` Called on time `()` ,Not called when clicking --> <input v-on:="submit" type="text" value="Click me 777" /> <!-- You can directly Any exposed valid key name is converted to kebab-case Come as a modifier。--> <input v-on:-down="onPageDown" type="text" value="Click me 888" /> <!-- In the above example,The processing function will only be in $ equal PageDown Called when。And the cursor works when it is there。 -->
System modifier
The following modifier can be used to implement a listener that triggers a mouse or keyboard event only when the corresponding key is pressed.
- .ctrl
- .alt
- .shift
- .meta
Note: On the Mac system keyboard, meta corresponds to the command key (⌘). On the Windows system keyboard meta corresponds to the Windows logo key (⊞). On the Sun operating system keyboard, meta corresponds to the solid gem key (◆). On other specific keyboards, especially on the keyboards of MIT and Lisp machines, and their successors, such as the Knight keyboard and the space-cadet keyboard, meta is marked "META". On the Symbolics keyboard, meta is marked as "META" or "Meta".
<!-- Alt + C --> <input @.67="clear"> <!-- Ctrl + Click --> <div @="doSomething">Do something</div>
Please note: The modifier key is different from the regular key. When used with the keyup event, the modifier key must be pressed when the event is triggered. In other words, it can only be triggered if other keys are released while holding down ctrl. Releasing ctrl will not trigger the event. If you want this behavior, please switch to keyCode: keyup.17 for ctrl.
.exact modifier
The .exact modifier allows you to control events triggered by precise combinations of system modifiers.
<!-- even though Alt or Shift It will also trigger when pressed together --> <button @="onClick">A</button> <!-- There are and only Ctrl Triggered only when pressed --> <button @="onCtrlClick">A</button> <!-- 没有任何系统修饰符Triggered only when pressed --> <button @="onClick">A</button>
Mouse button modifier
These modifiers restrict the handler to respond only to specific mouse buttons, as shown below:
- .left
- .right
- .middle
Why listen for events in HTML?
You may have noticed that this kind of event monitoring goes against the long-standing tradition of separation of concern. But don't worry, because all event handling methods and expressions are strictly bound to the ViewModel of the current view, which will not cause any maintenance difficulties. In fact, there are several benefits to using v-on:
- Scan the HTML template to easily locate the corresponding methods in JavaScript code.
- Because you don't have to manually bind events in JavaScript, your ViewModel code can be very pure logic, completely decoupled from the DOM, making it easier to test.
- When a ViewModel is destroyed, all event processors are automatically deleted. You don't have to worry about how to clean them up.
All the codes in this example are as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Event handling</title> <!-- Development environment version,Contains helpful command line warnings --> <script src="/npm/vue/dist/"></script> </head> <body> <div > <h2>Listen to events</h2> <!-- Can be used v-on Instruction monitoring DOM event,And run some when triggered JavaScript Code。 --> <button v-on:click="counter += 1">Add 1</button> <p>The button was clicked {{ counter }} Second-rate.</p> <h2>Event handling方法</h2> <!-- 然and许多Event handling逻辑会更for复杂,So just JavaScript Code写exist v-on It is not feasible in the instruction。 therefore v-on You can also receive a method name that needs to be called。 --> <!-- `greet` It is the method name defined below --> <button v-on:click="greet">Greet</button> <!-- // You can also use JavaScript to directly call methods //() // => 'Hello !' --> <h2>Methods in inline processors</h2> <!-- In addition to directly binding to a method,Can also be inlined JavaScript Calling methods in statements: --> <button v-on:click="say('hi')">Say hi</button> <button v-on:click="say('what')">Say what</button> <!-- Sometimes it is also necessary to access the original inline statement processor DOM event。Can be used特殊变量 $event Pass it into the method: --> <br> <button v-on:click="warn('Forms cannot be submitted.', $event)">submit</button> <h2>eventModifier</h2> <!-- existEvent handling程序中调use () or () It's a very common requirement。 Although we can easily implement this in our method,But the better way is:The method has pure data logic,Instead of dealing with it DOM event细节。 To solve this problem, for v-on 提供了eventModifier。As mentioned before,The modifier is represented by the suffix of the instruction starting with the dot.。 .stop •.prevent •.capture •.self •.once •.passive --> <!-- 阻止单击event继续传播 --> <a v-on:="doThis">Click666</a> <br> <!-- submitevent不再重载页面 --> <form v-on:="onSubmit"> <div> 阻止submit </div> </form> <br> <!-- Modifiers can be concatenated --> <a v-on:="doThat"></a> <br> <!-- Only modifiers --> <form v-on:> <div > Only modifiers </div> </form> <br> <!-- 添加event监听器时使useeventcapture模式 --> <!-- 即内部元素触发的event先exist此处理,Then it is handed over to the internal element for processing --> <div v-on:="doThis">doThis...</div> <br> <!-- Just as The processing function is triggered when the current element itself --> <!-- 即event不yes从内部元素触发的 --> <div v-on:="doThat">doThat...</div> <!-- When using modifiers,The order is important;相应的Code会以同样的顺序产生。 therefore,use v-on: 会阻止所有的Click,and v-on: 只会阻止对元素自身的Click。 --> <h2>New</h2> <!-- Clickevent将只会触发一Second-rate --> <a v-on:="doThis">点我一Second-rate666</a> <!-- Unlike other native ones DOM event起作use的Modifier,.once Modifier还能被use到自定义的组件eventsuperior。 --> <!-- Vue Also corresponding addEventListener In-house passive Options are provided .passive Modifier。 --> <!-- 滚动event的默认行for (即滚动行for) Will trigger immediately --> <!-- and不会等待 `onScroll` Finish --> <!-- This includes `()` The situation --> <div v-on:="onScroll">...</div> <!-- this .passive Modifier尤其能够提升移动端的性能。 !Don't put it .passive and .prevent 一起使use,因for .prevent Will be ignored,At the same time, the browser may show you a warning。 Please remember,.passive 会告诉浏览器你不想阻止event的默认行for。 --> <h2>按keyModifier</h2> <!-- exist监听key盘event时,We often need to check the detailed keys。Vue 允许for v-on exist监听key盘event时添加按keyModifier: --> <!-- Only in `key` yes `Enter` 时调use `()` ,Click时不调use --> <input v-on:="submit" type="text" value="Click me 777" /> <!-- You can directly 暴露的任意有效按key名转换for kebab-case 来作forModifier。 --> <input v-on:-down="onPageDown" type="text" value="Click me 888" /> <!-- In the above example,The processing function will only be in $ equal PageDown 时被调use。且光标exist时才管use。 --> <h2>#Key Code</h2> <!-- keyCode 的eventuse法已经被废弃了并可能不会被最新的浏览器支持。 使use keyCode attribute 也yes允许的: --> <input v-on:keyup.13="submit" type="button" value="key up 13"> <!-- for了exist必要The situation下支持旧浏览器,Vue 提供了绝大多数常use的按key码的别名: .enter •.tab •.delete (capture“delete”and“Backspace”key) •.esc •.space •.up •.down •.left •.right !有一些按key (.esc 以及所有的方向key) exist IE9 There are different key value, If you want to support IE9,这些内置的别名应该yes首选。 You can also pass the global 对象自定义按keyModifier别名: // You can use `v-on:keyup.f1` .f1 = 112 --> <h2>系统修饰key</h2> <!-- Can be used如下Modifier来实现仅exist按下相应按key时才触发鼠标orkey盘event的监听器。 .ctrl •.alt •.shift •.meta Notice:exist Mac 系统key盘superior,meta correspond command key (⌘)。 exist Windows 系统key盘 meta correspond Windows 徽标key (⊞)。exist Sun 操作系统key盘superior,meta correspond实心宝石key (◆)。 exist其他特定key盘superior,尤其exist MIT and Lisp 机器的key盘、And its successor products,for example Knight key盘、space-cadet key盘,meta 被标记for“META”。 exist Symbolics key盘superior,meta 被标记for“META”or者“Meta”。 --> <!-- Alt + C --> <input @.67="clear"> <!-- Ctrl + Click --> <div @="doSomething">Do something</div> <!-- !请Notice修饰key与常规按key不同,existand keyup event一起use时,event触发时修饰key必须处于按下状态。 in other words,Only in按住 ctrl The situation下释放其它按key,Only trigger 。and单单释放 ctrl 也不会触发event。 如果你想要这样的行for,请for ctrl 换use keyCode:keyup.17。 --> <h2>#.exact modifier</h2> <!-- .exact Modifier允许你控制由精确的系统Modifier组合触发的event。 --> <!-- even though Alt or Shift It will also trigger when pressed together --> <button @="onClick">A</button> <!-- There are and only Ctrl Triggered only when pressed --> <button @="onCtrlClick">A</button> <!-- 没有任何系统ModifierTriggered only when pressed --> <button @="onClick">A</button> <h2>#Mouse Button Modifier</h2> <!-- .left •.right •.middle 这些Modifier会限制处理函数仅响应特定的鼠标按钮。 --> <h2>for什么exist HTML 中Listen to events?</h2> <!-- 你可能Notice到这种event监听的方式违背了关注点分离 (separation of concern) this长期以来的优良传统。 But don't worry,因for所有的 Event handling方法and表达式都严格绑定exist当前视图的 ViewModel superior,它不会导致任何维护superior的困难。 实际superior,使use v-on There are several benefits: 1.Scan the eyes HTML 模板便能轻松定位exist JavaScript Code里correspond的方法。 2.因for你无须exist JavaScript 里手动绑定event,your ViewModel Code可以yes非常纯粹的逻辑,and DOM Completely decoupled,Easier to test。 3.When a ViewModel When destroyed,所有的Event handling器都会自动被delete。You don't have to worry about how to clean them。 --> </div> <script type="text/javascript"> var app=new Vue({ el:'#app', data:{ msg:'hello world!!!', counter:0, name: '' }, // Define methods in the `methods` object methods:{ greet: function (event) { // `this` points to the current Vue instance in the method alert('Hello ' + + '!') // `event` is a native DOM event if (event) { alert() } }, say: function (message) { alert(message); }, warn: function (message, event) { // Now we can access the native event object if (event) { (); } alert(message); }, doThis:function(){ alert('Click me 666'); }, doThat:function(){ alert('Click it 666'); }, submit:function(){ alert('Click me--submit'); }, onPageDown:function(){ alert('Click me --onPageDown'); }, doSomething:function(){ alert('Click me --doSomething'); }, clear:function(){ alert('Click me--clear'); }, onClick:function(){ alert('Click me --onClick'); }, onCtrlClick:function(){ alert('Click me --onCtrlClick'); } } }); </script> </body> </html>
The above is a detailed explanation of the detailed content of Vue's event handling. For more information about Vue's event handling, please follow my other related articles!