Vue-native綁定原生事件


首先介紹一下是什么意思:

意思就是當你給一個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 才會生效

 1 <div id = "app">
 2    <my-component @click.native="i_said"></my-component>
 3 </div>
 4 
 5 Vue.component('my-component', {
 6   template: "<button>點擊我</button>",
 7 })
 8 
 9 new Vue({
10   el:"#app",
11   methods:{
12     i_said(){
13        alert("Hello world");
14     }
15   }
16 })

 

這樣就能執行了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM