zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Vue的7种事件修饰符的使用

Vue事件 修饰符 使用
2023-09-11 14:21:26 时间

Vue中事件的基本使用

(1)使用v-on:xxx或@xxx绑定事件,其中xxx是事件名

(2)事件的回调需要配置在methods对象中,最终会出现在vm上

Vue中的事件修饰符

(1)prevent(常用:阻止默认事件发生

<a href="https://baidu.com" @click.prevent="showInfo">点我提示信息</a>

methods:{
    showInfo(){
        alert('欢迎学习Vue')
    }
}

//运行结果:a链接不会跳转到百度

(2)stop(常用):阻止事件冒泡

<div class="demo" @click="showInfo">
    <button @click.stop="showInfo">点我提示信息</button>
</div>

methods: {
    showInfo() {
        alert("欢迎学习Vue")
    }
},

//运行结果:点击button时,只有一次弹窗

(3)once(常用):事件只触发一次

<button @click.once="showInfo">点我提示信息</button>

methods: {
    showInfo() {
        alert("欢迎学习Vue")
    }
},

//运行结果:点击button时,只有第一次弹窗,再点弹窗失效

(4)capture:使用事件的捕获模式

<div @click.capture="showInfo(111)">
    111
    <button @click="showInfo(222)">222</button>
</div>

methods: {
    showInfo(value) {
        alert(value)
    }
},

//点击按钮,不加capture运行结果:先弹出222,再弹出111
//添加capture运行结果:先弹出111,再弹出222

(5)self:只有event.target是当前操作的元素是才触发事件

<div @click.self="showInfo(111)">
    111
    <button @click="showInfo(222)">222</button>
</div>

methods: {
    showInfo(value) {
        alert(value)
    }
},

//点击按钮,运行结果:弹出222

(6)passive:事件的默认行为立即执行,无需等待时间回调执行完毕

(7)native:将原生事件绑定到组件

在一个组件的根元素上直接监听一个原生事件,可以使用.native 修饰符

<el-input name="password" @keyup.enter.native="handleLogin"/>

`@keyup.enter.native `表示监听组件的原生事件,比如 keyup就是于input的原生事件,这里写native表示keyup是一个原生事件