Recently, I learned vuejs to see an example using $on to not listen for the child component $emit trigger event:
Version of use
2.2.5
References
1.vuejs API
2.Solve examples
Problem analysis
1. The custom component event I wrote before is triggered as this.$emit("myclick",);, so this refers to each item of todo-item, and the last vm.$on listens to the app component, which means that it is the parent node and the child node is the one that is triggered, so this event cannot be listened to.
Solution
1. Put the trigger event on the parent node to trigger it, and you can listen to the triggered event, that is, this.$parent.$emit("myclick",);, so that you can listen to the triggered event in vm.$on.
Implement code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>EmitEvents andOnevent</title> </head> <script src="../js/"></script> <link rel="stylesheet" href="../css/" rel="external nofollow" /> <body> <div > <todo-item v-for="(item,index) in items" v-bind:todo="item" v-on:myclick="addResult"></todo-item> </div> </body> <script> ('todoItem',{ props:['todo'], template:'<li v-on:click="add">{{}}</li>', //1. Add click event to add to the custom component methods:{ add:function(){ //2. Here add gets the click event add in the template and executes the function this.$parent.$emit("myclick",); //3.Expose to the parent component to the click event name is my-click }, }, }) var vm=new Vue({ el:'#app', data:{ items:[ { text: 'Runoob' }, { text: 'Google' }, { text: 'Taobao' } ] }, methods:{ //5. Here, execute the click function passed by the parent component. addResult:function(value){ alert(value); }, }, }); vm.$on('myclick',function (value) { (value); }) </script> </html>
The above article solves the problem that the parent component $on cannot listen to the child component $emit trigger event is all the content I have shared with you. I hope it can give you a reference and I hope you can support me more.