Detailed example of event modifiers in Vue
Event Modifier
In Vue, Event Modifier handles the details of many DOM events , so that we no longer need to spend a lot of time dealing with these annoying things, but can have more energy to focus on the logical processing of the program. (Learning video sharing: vue video tutorial)
The main event modifiers in Vue are:
-
.stop
: Equivalent toevent.stopPropagation()
in JavaScript, preventing events from bubbling -
.prevent
: Equivalentevent.preventDefault()
in JavaScript prevents the execution of the default behavior (if the event can be canceled, cancel the event without stopping the further propagation of the event) -
.capture
: Contrary to the direction of event bubbling, event capture is from outside to inside -
.self
: It will only trigger Events within its own scope, excluding child elements .once
: will only be triggered once
Next, let's look at the role of event modifiers through some simple examples.
.stop Prevent event bubbling
Bubble events: nest two or three layers of parent-child relationships, and then all have click events. Click on the child node to trigger From inside to outside, click event of child node->parent node
<!-- HTML --> <div> <div> <div> <button>点击我(^_^)</button> </div> </div> <p>{{ message }}</p> </div> let app = new Vue({ el: '#app', data () { return { message: '测试冒泡事件' } }, methods: { inner: function () { this.message = 'inner: 这是最里面的Button' }, middle: function () { this.message = 'middle: 这是中间的Div' }, outer: function () { this.message = 'outer: 这是外面的Div' } } })
The diagram of the entire event is as follows:
The way to prevent bubbling events is: adding .stop
to the click is equivalent to calling the equivalent of event.stopPropagation()
in each method. Clicking on child nodes will not capture it. Events to the parent node
<!-- HTML --> <div id="app"> <div class="outeer" @click.stop="outer"> <div class="middle" @click.stop="middle"> <button @click.stop="inner">点击我(^_^)</button> </div> </div> </div>
At this time, when the button is clicked, the events on div.middle and div.outer will not be captured:
.preventCancel the default event
.prevent
is equivalent to JavaScript's event.preventDefault()
, used to cancel the default event. For example, when the user clicks on the <a href="#">
tag on our page, # is usually listed in the browser's URL:
In JavaScript, event.preventDefault()
is often used to prevent # from appearing in the browser's URL. In Vue, you can use the event modifier .prevent
to cancel the default event. At this time, after clicking the link, # will no longer appear in the browser's URL.
<div id="app"> <a href="#" @click.prevent="prompt">点击我(^_^)</a> <p>{{ message }}</p> </div> let app = new Vue({ el: '#app', data () { return { message: '我是一个文本信息' } }, methods: { prompt: function (e) { this.message = location.href } } })
.capture Capture event
Capture event: nest two or three layers of parent-child relationships, and then all have click events, Clicking on a child node will trigger a click event from the outside to the parent node -> child node. The
.capture
modifier is exactly the opposite of the .stop
. .stop
is to prevent events from bubbling, while .capture
is similar to JavaScript event capture, which is from outside to inside. As shown in the figure below:
Used in our Vue event modifier:
<!-- HTML --> <div id="app"> <div class="outeer" @click.capture="outer"> <div class="middle" @click.capture="middle"> <button @click.capture="inner">点击我(^_^)</button> </div> </div> <p>{{ message }}</p> </div> let app = new Vue({ el: '#app', data () { return { message: '事件捕获' } }, methods: { inner: function () { this.message = 'inner: 这是最里面的Button' alert(this.message) }, middle: function () { this.message = 'middle: 这是中间的Div' alert(this.message) }, outer: function () { this.message = 'outer: 这是外面的Div' alert(this.message) } } })
The behavior seen is as follows:
.self
Modifier .self
will only trigger events within its own scope and will not include child elements.
<!-- HTML --> <div id="app"> <div class="outer" @click.self="outer"> <div class="middle" @click.self="middle"> <button @click="inner">点击我(^_^)</button> </div> </div> <p>{{ message }}</p> </div> let app = new Vue({ el: '#app', data () { return { message: '修饰符:.self' } }, methods: { inner: function () { this.message = 'inner: 这是最里面的Button' alert(this.message) }, middle: function () { this.message = 'middle: 这是中间的Div' alert(this.message) }, outer: function () { this.message = 'outer: 这是外面的Div' alert(this.message) } } })
We clicked on div.outer
, div.middle
and button
respectively, and click events were bound to these elements. , and added the .self modifier:
.once only executes one click
Remember we used Vue to write it before For a counter, click
and it will increase by 1. If you continue to click, it will continue to accumulate. On the contrary, if you click on -
, it will decrease by 1. If you continue to click, it will continue to decrease.
<div id="app"> <button v-on:click="increase">+</button> <span>{{ count }}</span> <button v-on:click="reduce">-</button> </div> let app = new Vue({ el: '#app', methods: { increase: function() { this.count++ }, reduce: function() { this.count-- } }, data: { count: 0 } })
If we add the .once
modifier on the @click
event, it will only be executed once when the button is clicked.
<div id="app"> <button @click.once="increase">+</button> <span>{{ count }}</span> <button @click.once="decrease">-</button> </div>
Demo address: https://codepen.io/airen/pen/dVQoRN
键盘修饰符
在JavaScript事件中除了前面所说的事件,还有键盘事件,也经常需要监测常见的键值。在Vue中允许v-on
在监听键盘事件时添加关键修饰符。记住所有的keyCode
比较困难,所以Vue为最常用的键盘事件提供了别名:
.enter
:回车键.tab
:制表键.delete
:含delete
和backspace
键.esc
:返回键.space
: 空格键.up
:向上键.down
:向下键.left
:向左键.right
:向右键
<div id="app"> <button @keyup.enter="enter" @keyup.tab="tab" @keyup.delete="delete1" @keyup.esc="esc" @keyup.space="space" @keyup.up="up" @keyup.down="down" @keyup.left="left" @keyup.right="right">{{ message }}</button> <p>{{ message }}</p> </div> let app = new Vue({ el: '#app', data () { return { message: '将光标置于按钮上后,按下键盘上不同的按键,会有不同的效果' } }, methods: { enter: function (){ this.message = '你按了回车键:enter' }, tab: function (){ this.message = '你按了tab键: tab' }, delete1: function (){ this.message = '你按了删除键: delete' }, esc: function (){ this.message = '你按了取消键: esc' }, space: function (){ this.message = '你按了空格键:space' }, up: function (){ this.message = '你按了向上键:up' }, down: function (){ this.message = '你按了向下键:down' }, left: function (){ this.message = '你按了向左键:left' }, right: function (){ this.message = '你按了向右键:right' } } })
当你把鼠标移动按钮上,然后按下不同的键盘,将会监听到对应的键盘事件:
演示demo地址::https://codepen.io/airen/pen/RLqPYx
鼠标修饰符
鼠标修饰符用来限制处理程序监听特定的滑鼠按键。常见的有:
.left
:鼠标左键.middle
:鼠标中间滚轮.right
:鼠标右键
修饰键
可以用如下修饰符开启鼠标或键盘事件监听,使在按键按下时发生响应:
.ctrl
.alt
.shift
.meta
自定义按键修饰符别名
在Vue中可以通过config.keyCodes
自定义按键修饰符别名。例如,由于预先定义了keycode 116
(即F5
)的别名为f5
,因此在文字输入框中按下F5
,会触发prompt
方法,出现alert
。
<!-- HTML --> <div id="app"> <input type="text" v-on:keydown.f5="prompt()"> </div> Vue.config.keyCodes.f5 = 116; let app = new Vue({ el: '#app', methods: { prompt: function() { alert('我是 F5!'); } } });
总结
在Vue中,使用v-on
来给元素绑定事件,而为了更好的处理逻辑方面的事物,Vue提供了一个methods
。在methods
中定义一些方法,这些方法可以帮助我们处理一些逻辑方面的事情。而在这篇文章中,我们主要介绍了一些事件的修饰符,比如常见的阻止事件冒泡,键盘修饰符等。除此之外,还提供了config.keyCodes
提供自定义按键修饰符别名。
The above is the detailed content of Detailed example of event modifiers in Vue. 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











Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.
