Vue @click.native 的作用


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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM