关于vue中@click.native
.native - 侦听组件根元素上的原生事件
作用:[给组件绑定原生事件]
例子:如果使用router-link标签,加上@click事件,绑定的事件会无效因为:router-link的作用是单纯的路由跳转,会阻止click事件,你可以试试只用click不用native,事件是不会触发的。此时加上.native,才会触发事件。
@ 这个东西实际上是 v-on 的简写,而 v-on 则是对 Vue 的事件体系封装后的 API 接口。
Vue 的官方文档中指出了,Vue 使用的是一套自己的事件传递机制,如 @click 等事件是经过 Vue 封装的。因此,在一些实际上处理 DOM 原生事件的场合才需要添加额外的标识符。
意思就是当你给一个vue组件绑定事件时候,要加上native!如果是普通的html元素!就不需要
<div id = "app">
<my-component @click="i_said"></my-component>
</div>
Vue.component('my-component', {
template: "<button>点击我</button>",
})
new Vue({
el:"#app",
methods:{
i_said(){
alert("Hello world");
}
}
})
这样在组件上添加事件是没有效果的,如果是普通的html标签当然没问题比如
<div id = "app">
<button @click="i_said">点击我</button>
</div>
new Vue({
el:"#app",
methods:{
i_said(){
alert("Hello world");
}
}
})
这样肯定没问题,
组件上添加自定义事件也没问题比如
<div id = "app">
<my-component @say="i_said"></my-component>
</div>
Vue.component("my-component", {
template: "<button @click='greet'>点击我</button>",
methods:{
greet(){
this.$emit("say", "Hello world");
}
}
})
new Vue({
el:"#app",
methods:{
i_said(message){
alert(message)
}
}
})
这样也完全没有问题也直接弹出“Hello world”
但是组件要添加原生事件需要加上.native 才会生效
<div id = "app">
<my-component @click.native="i_said"></my-component>
</div>
Vue.component('my-component', {
template: "<button>点击我</button>",
})
new Vue({
el:"#app",
methods:{
i_said(){
alert("Hello world");
}
}
})
这样就能执行了!