Table of Contents
Event Modifier
.stop Prevent event bubbling
.preventCancel the default event
.capture Capture event
.self
.once only executes one click
键盘修饰符
鼠标修饰符
修饰键
自定义按键修饰符别名
总结
Home Web Front-end Vue.js Detailed example of event modifiers in Vue

Detailed example of event modifiers in Vue

Aug 10, 2022 pm 04:38 PM
vue event modifier

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 to event.stopPropagation() in JavaScript, preventing events from bubbling
  • .prevent: Equivalent event.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'
        }
    }
})
Copy after login

Detailed example of event modifiers in Vue

The diagram of the entire event is as follows:

Detailed example of event modifiers in Vue

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>
Copy after login

At this time, when the button is clicked, the events on div.middle and div.outer will not be captured:

Detailed example of event modifiers in Vue

.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:

Detailed example of event modifiers in Vue

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: &#39;#app&#39;,
  data () {
    return {
      message: &#39;我是一个文本信息&#39;
    }
  },
  methods: {
    prompt: function (e) {
      this.message = location.href
    }
  }
})
Copy after login

Detailed example of event modifiers in Vue

.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: &#39;#app&#39;,
    data () {
        return {
            message: &#39;事件捕获&#39;
        }
    },
    methods: {
        inner: function () {
            this.message = &#39;inner: 这是最里面的Button&#39;
            alert(this.message)
        },
        middle: function () {
            this.message = &#39;middle: 这是中间的Div&#39;
            alert(this.message)
        },
        outer: function () {
            this.message = &#39;outer: 这是外面的Div&#39;
            alert(this.message)
        }
    }
})
Copy after login

The behavior seen is as follows:

Detailed example of event modifiers in Vue

.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: &#39;#app&#39;,
    data () {
        return {
            message: &#39;修饰符:.self&#39;
        }
    },
    methods: {
        inner: function () {
            this.message = &#39;inner: 这是最里面的Button&#39;
            alert(this.message)
        },
        middle: function () {
            this.message = &#39;middle: 这是中间的Div&#39;
            alert(this.message)
        },
        outer: function () {
            this.message = &#39;outer: 这是外面的Div&#39;
            alert(this.message)
        }
    }
})
Copy after login

We clicked on div.outer, div.middle and button respectively, and click events were bound to these elements. , and added the .self modifier:

Detailed example of event modifiers in Vue

.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: &#39;#app&#39;,
    methods: {
        increase: function() {
            this.count++
        },
        reduce: function() {
            this.count--
        }
    },
    data: {
        count: 0
    }
})
Copy after login

Detailed example of event modifiers in Vue

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>
Copy after login

Detailed example of event modifiers in Vue

Demo address: https://codepen.io/airen/pen/dVQoRN

键盘修饰符


在JavaScript事件中除了前面所说的事件,还有键盘事件,也经常需要监测常见的键值。在Vue中允许v-on在监听键盘事件时添加关键修饰符。记住所有的keyCode比较困难,所以Vue为最常用的键盘事件提供了别名:

  • .enter:回车键
  • .tab:制表键
  • .delete:含deletebackspace
  • .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: &#39;#app&#39;,
  data () {
    return {
      message: &#39;将光标置于按钮上后,按下键盘上不同的按键,会有不同的效果&#39;
    }
  },
  methods: {
    enter: function (){
      this.message = &#39;你按了回车键:enter&#39;
    },
    tab: function (){
      this.message = &#39;你按了tab键: tab&#39;
    },
    delete1: function (){
      this.message = &#39;你按了删除键: delete&#39;
    }, 
    esc: function (){
      this.message = &#39;你按了取消键: esc&#39;
    },
    space: function (){
      this.message = &#39;你按了空格键:space&#39;
    },
    up: function (){
      this.message = &#39;你按了向上键:up&#39;
    },
    down: function (){
      this.message = &#39;你按了向下键:down&#39;
    },
    left: function (){
      this.message = &#39;你按了向左键:left&#39;
    },
    right: function (){
      this.message = &#39;你按了向右键:right&#39;
    }
  }
})
Copy after login

当你把鼠标移动按钮上,然后按下不同的键盘,将会监听到对应的键盘事件:

Detailed example of event modifiers in Vue

演示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: &#39;#app&#39;,
    methods: {
        prompt: function() {
            alert(&#39;我是 F5!&#39;);
        }
    }
});
Copy after login

总结


在Vue中,使用v-on来给元素绑定事件,而为了更好的处理逻辑方面的事物,Vue提供了一个methods。在methods中定义一些方法,这些方法可以帮助我们处理一些逻辑方面的事情。而在这篇文章中,我们主要介绍了一些事件的修饰符,比如常见的阻止事件冒泡,键盘修饰符等。除此之外,还提供了config.keyCodes提供自定义按键修饰符别名。

(学习视频分享:web前端开发编程基础视频

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

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.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

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.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

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.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

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

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

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.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

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

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

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

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

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.

See all articles