@click.native

关于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");
    }
   }
 })

 

这样就能执行了!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值