其他分享
首页 > 其他分享> > Vue组件之间的通信(子传父)

Vue组件之间的通信(子传父)

作者:互联网

源码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 8   <title>Document</title>
 9 </head>
10 
11 <body>
12   <!--父组件模版-->
13   <div id='content'>
14     <cpn @itemclick="itemClick"></cpn>
15   </div>
16 
17   <!--子组件模版-->
18   <template id="myCpn">
19     <div>
20       <button v-for="item in classification" @click="itemclick(item)">{{item.name}}</button>
21     </div>
22   </template>
23 
24   <script src='../Vue/vue.js'></script>
25   <script>
26     //子组件
27     const cpn = {
28       template: "#myCpn",
29       data() {
30         return {
31           classification: [
32             { id: "aa", name: "数码电脑" },
33             { id: "bb", name: "情趣计生" },
34             { id: "cc", name: "服装鞋袜" },
35             { id: "dd", name: "食品安全" },
36             { id: "ee", name: "生鲜水果" },
37           ],
38         };
39       },
40       methods: {
41         itemclick:function(item){
42           this.$emit("itemclick",item);
43         },
44       },
45       props: {
46 
47       },
48     };
49     //父组件
50     const content = new Vue({
51       el: '#content',
52       data: {
53 
54       },
55       methods: {
56         itemClick:(item)=>{
57           console.log(item);
58         },
59       },
60       components: {
61         cpn
62       }
63     });
64   </script>
65 </body>
66 
67 </html>

说明

1、子组件使用$emit发射事件,后面可以跟一个参数,如图

2、父组件中接收事件,默认接收子组件传递过来的参数,所以当需要接收子组件传递过来的参数时,通常不用写括弧。如图

标签:itemclick,Vue,子传父,methods,item,组件,id,name
来源: https://www.cnblogs.com/bihuijia/p/14397163.html