Table of Contents
v-on command introduction
点击我
v-on example
Home Web Front-end Vue.js Let's talk about Vue's event monitoring instruction v-on

Let's talk about Vue's event monitoring instruction v-on

Aug 10, 2022 pm 03:30 PM
vue event listening v-on

In front-end development, we need to interact with users frequently. At this time, we must monitor user events, such as clicks, drags, keyboard events, etc. How to monitor events in Vue? Use the v-on directive. The following article will take you through Vue's event monitoring command v-on. I hope it will be helpful to you!

Let's talk about Vue's event monitoring instruction v-on

v-on command introduction

  • Function: Binding Defined event listener

  • Abbreviation: @

  • Expected: Function (method) | Inline Statement (internal expression) | Object (object)

  • Parameters: event

Bind event listeners in Vue. The event type is specified by parameters; the expression can be the name of a method or an inline statement, which can be omitted if there are no modifiers. (Learning video sharing: vue video tutorial)

Starting from v2.4.0, v-on also supports binding an event/listener key-value pair without parameters Object. Note that when using object syntax, no modifiers are supported.

When used on ordinary elements, it can only listen to native DOM events. When used on a custom element component, you can also listen to custom events triggered by child components.

When listening to native DOM events, the method takes the event as the only parameter. If using an inline statement, the statement can access an $event attribute: v-on:click="handle('ok', $event)".

Let’s look at a simple example first

<!-- Template -->
<div id="app">
    <h1 id="点击我">点击我</h1>   
</div>

// JavaScript
var app = new Vue({
    el: &#39;#app&#39;,
    methods: {
        clickMe: function() {
            alert("点击我,我就出来了!(^_^)")
        }
    },
    data: {
    }
})
Copy after login

The effect you see is as follows:

Lets talk about Vues event monitoring instruction v-on

In the Vue template, we use v-on, and bind a click event (v-on:click), and then bind this click event An event clickMe was triggered. And this clickMe in Vue, we usually put it in methods: {}, that is to say, the clickMe function is written in methodsmiddle.

See v-on:click="clickMe", is it very similar to onclock="clickMe" in HTML? Judging from the appearance, their writing methods are different, but the results are the same. In Vue, we can also use @click instead of v-on:click. Then they play the same role.

In Vue, in addition to the above examples, there are also the following usage methods for v-on:

<!-- 方法处理器 -->
<button v-on:click="clickMe"></button>

<!-- 对象语法 (v2.4.0版本以上才支持) -->
<button v-on="{ mousedown: doThis, mouseup: doThat}"></button>

<!-- 内联语句 -->
<button v-on:click="doThat(&#39;Hello&#39;, $event)"></button>

<!-- 缩写 -->
<button @click="doThis"></button>

<!-- 停止冒泡 -->
<button @click.stop="doThis"></button>

<!-- 阻止默认行为 -->
<button @click.prevent="doThis"></button>

<!-- 阻止默认行为, 没有表达式 -->
<form @submit.prevent></form>

<!-- 串联修饰符 -->
<button @click.stop.prevent="doThis"></button>

<!-- 键修饰符, 键别名 -->
<input @keyup.13="onEnter" />

<!-- 点击回调只会触发一次 -->
<button v-on:click.once="doThis"></button>
Copy after login

on subcomponents Listen to custom events (the event handler will be called when the subcomponent triggers my-event):

<my-component @my-event="handleThis"></my-component>
<!-- 内联语句 -->
<my-component @my-event="handleThis(123, $event)"></my-component>
<!-- 组件中的原生事件 -->
<my-component @click.native="onClick"></my-component>
Copy after login

From the above simple example, you can see that Vue is in the process of event processing It comes with some modifiers:

  • .stop: Call event.stopPropagation()

  • . prevent: Call event.preventDefault()

  • .capture: Use capture mode when adding event listeners

  • .self: The callback is only triggered when the event is triggered from the element itself to which the listener is bound

  • .{keyCode | keyAlias }: Trigger the callback only when the event is triggered from a specific key

  • .native: Listen to the native event of the component root element

  • .once: Only triggers the callback once

  • .left: Only triggers when the left mouse button is clicked. (Only available in v2.2.0)

  • .right: Triggered only when the right mouse button is clicked, (Only available on v2.2.0)

  • .middle: Only triggered when the middle mouse button is clicked, (only available in v2.2.0)

  • .passive : Add a listener in {passive: true} mode, (only available in v2.3.0)

Vue’s official website handles events and customizes components events are described in detail. If you are interested, you can view the corresponding content:

v-on example

Let’s make a simple effect, which is a counter. The effect is as follows:

Lets talk about Vues event monitoring instruction v-on

This effect is very simple. Click to increase the number, and click - to decrease the number.

In Vue, our template has three elements, two buttons, and a container that displays numbers. The first button does addition calculations, and the second button does subtraction counting. The simple structure is as follows:

<div id="app">
    <button v-on:click="increase">+</button>
    <span>{{ count }}</span>
    <button v-on:click="reduce">-</button>
</div>
Copy after login

两个按钮上都绑定了一个click事件,点击按钮分别触发increasereduce两个函数,前者做加法,后者做减法。另外一个元素中我们有一个值{{ count }}。每次点击按钮这个{{ count }}都会做相应的变化。

模板有了之后,需要添加对应的功能。

let app = new Vue({
    el: &#39;#app&#39;,
    methods: {
        increase: function() {
            this.count++
        },
        reduce: function() {
            this.count--
        }
    },
    data: {
        count: 0
    }
})
Copy after login

在Vue中,我们在methods中声明了两个函数,分别是increase(加法)和reduce(减法)。另外需要在数据源中声明count

演示demo地址:https://codepen.io/airen/pen/PJbKNg

对于这么简单的效果,我们也可以直接在v-on中处理完:

<button v-on:click="count += 1">+</button>
Copy after login

比如我们前面的示例,修改下:

<button v-on:click="count += 1">+</button> {{ count }}
// JavaScript let app = new Vue({ el: '#app', data: { count: 0 } })
Copy after login

效果一样:

Lets talk about Vues event monitoring instruction v-on

演示demo地址:https://codepen.io/airen/pen/veyeLY

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

The above is the detailed content of Let's talk about Vue's event monitoring instruction v-on. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

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

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.

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.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles