Issues with Vue methods and event handling
Method and event processor
Method processor
You can use the v-on
command to monitor DOM events:
<p id="example"> <button v-on:click="greet">Greet</button> </p>
We are bound A click event handler to a method greet
. Define this method in the Vue instance below:
var vm = new Vue({ el: '#example', data: { name: 'Vue.js' }, // 在 `methods` 对象中定义方法 methods: { greet: function (event) { // 方法内 `this` 指向 vm alert('Hello ' + this.name + '!') // `event` 是原生 DOM 事件 alert(event.target.tagName) } } }) // 也可以在 JavaScript 代码中调用方法 vm.greet() // -> 'Hello Vue.js!'
Inline statement processor
In addition to directly binding to a method, you can also use inline JavaScript statements:
<p id="example-2"> <button v-on:click="say('hi')">Say Hi</button> <button v-on:click="say('what')">Say What</button> </p> new Vue({ el: '#example-2', methods: { say: function (msg) { alert(msg) } } }
Similar to inline expressions, event handlers are limited to one statement.
Sometimes it is also necessary to access native DOM events in an inline statement processor. You can use the special variable $event
to pass it into the method:
<button v-on:click="say('hello!', $event)">Submit</button>
// ... methods: { say: function (msg, event) { // 现在我们可以访问原生事件对象 event.preventDefault() } }
Event modifier
often needs to be called in the event handler event.preventDefault()
or event.stopPropagation()
. Although we can easily do this within a method, it would be better to have the method be pure data logic and not deal with DOM event details.
In order to solve this problem, Vue.js provides two event modifiers for v-on
: .prevent
and .stop
. Do you still remember that modifiers are command suffixes starting with a period?
<!-- 阻止单击事件冒泡 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 --> <form v-on:submit.prevent="onSubmit"></form> <!-- 修饰符可以串联 --> <a v-on:click.stop.prevent="doThat"> <!-- 只有修饰符 --> <form v-on:submit.prevent></form>
1.0.16 Added two additional modifiers:
<!-- 添加事件侦听器时使用 capture 模式 --> <p v-on:click.capture="doThis">...</p> <!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 --> <p v-on:click.self="doThat">...</p>
Key modifiers
When listening for keyboard events, we often need to detect keyCode. Vue.js allows adding key modifiers for v-on
:
<!-- 只有在 keyCode 是 13 时调用 vm.submit() --> <input v-on:keyup.13="submit">
It is difficult to remember all the keyCode, Vue.js provides aliases for the most commonly used keys:
<!-- 同上 --> <input v-on:keyup.enter="submit"> <!-- 缩写语法 --> <input @keyup.enter="submit">
enter tab delete esc space up down left right
1.0.8+: Supports single-letter key aliases.
1.0.17+: You can customize the key alias:
// 可以使用 @keyup.f1 Vue.directive('on').keyCodes.f1 = 112
Why listen for events in HTML?
You may notice that this way of event monitoring goes against the tradition Concept "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 several advantages:
You can easily locate the corresponding method in the JavaScript code by scanning the HTML template.
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.
When a ViewModel is destroyed, all event handlers will be automatically deleted. You don’t have to worry about cleaning them yourself.
The above is the detailed content of Issues with Vue methods and event handling. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

What are the questions involved in the Yulong 8 Wine Master exam? What is the corresponding answer? How to pass the exam quickly? There are many questions that need to be answered in the Master of Wine Examination activities, and we can refer to the answers to solve them. These questions all involve knowledge of wine. If you need a reference, let’s take a look at the detailed analysis of the answers to the Yakuza 8 Wine Master exam questions! Detailed explanation of answers to questions in the Rulong 8 Wine Master exam 1. Questions about "wine". This is a distilled liquor produced by a distillery established by the royal family. It is brewed from the sugar of sugarcane grown in large quantities in Hawaii. What is the name of this wine? Answer: Rum 2. Question about "wine". The picture shows a drink made from dry ginseng and dry vermouth. It is characterized by the addition of olives and is known as "cockney"

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

Many users have tried to update the win11 system, but found that the start menu cannot be used after the update. This may be because there is a problem with the latest update. We can wait for Microsoft to fix or uninstall these updates to solve the problem. Let's take a look at it together. Solution. What to do if the start menu cannot be used after win11 is installed. Method 1: 1. First open the control panel in win11. 2. Then click the "Uninstall a program" button below the program. 3. Enter the uninstall interface and find "View installed updates" in the upper left corner. 4. After entering, you can view the update time in the update information and uninstall all recent updates. Method 2: 1. In addition, we can also directly download the win11 system without updates. 2. This is a product without the most

Wuhua Mixin has confirmed that it will conduct a breaking test on February 28. This time we will mainly solve the common problems of the breaking test, including whether you have participated in previous tests, are you eligible this time, the start and end of the test, and the pre-download time? Let’s take a look at what device platforms are supported and other content. Frequently Asked Questions about Wuhuami’s new breakthrough test: February 28, we look forward to your arrival! 1. What is the nature of the "breaking test"? This test is a limited billing and file deletion test for Android. After the test, the game data of this test will be deleted. 2. Have you ever participated in the "Opening Test" or "Entry Test"? Do you have the qualifications to participate in the "Breaking Test" this time? If you have participated in the "Opening Test" or "Entry Test", please scan the QR code below to go to " To players who have participated in the closed beta

Processing strings in PHP is a very common operation, and removing the first character on the right is also a common need. In this article, I will show you how to remove the first character on the right using PHP code. First, let's look at a simple example of a string processing function that demonstrates how to remove the first character on the right:
