1.首先, @click.native 是給組件綁定原生事件,只能用在組件上,不可以用在原生元素上。異常信息:
[vue warn]: The .native modifier for v-on is only valid on components but it was used on <button>.
2. 在組件上綁定@click="clickCpn"事件,click事件無法觸發也不生效,需要通過使用@click.native="clickCpn",才能夠執行clickCpn方法。
3. 除了 @click.native ,還可以在子組件中添加this.$emit ("click" ,value )方法 將子組件的值傳到父組件。但是這種方法相對麻煩,比如組件中有多個事件,需要重復添加$emit()方法。
廣州包裝設計公司http://www.maiqicn.com 電腦刺綉綉花廠 ttp://www.szhdn.com
代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vue 測試實例 - 菜鳥教程(runoob.com)</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> </head> <body> <div id="app"> <p>{{ message }}</p> <h1>{{form.title}}</h1> <button @click="changeMessage">切換</button> <br/> <cpn @click.native="clickCpn"></cpn> </div> <template id="cpn"> <div> <button @click="clickCpn1">組件點擊事件1</button> <button @click="clickCpn2">組件點擊事件2</button> </div> </template> <script> let cpn = { template: '#cpn', methods:{ clickCpn1(){ console.log("child1 click event"); //this.$emit('click'); }, clickCpn2(){ console.log("child2 click event"); //this.$emit('click'); } } } var app = new Vue({ el: '#app', data: { message: 'Hello Vue.js!', form:{ title: "標題黨" } }, components:{ cpn, }, watch: { 'form.title'(newVal, oldVal){ console.log(newVal + ' -- ' + oldVal); } }, methods: { changeMessage(){ this.form.title = 'helloworld' }, clickCpn(){ console.log("parent click event"); } } }) </script> </body> </html>
