1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9 </head>
10
11 <body>
12 <!-- 父组件模板 -->
13 <div id="app">
14 <!--子向父 将子组件事件与父组件事件进行绑定 |父向子 将父组件中categories与子组件中subcategories进行绑定-->
15 <cpn @itemclick="cpnclick" :subcategories="categories" :submessage="message"></cpn>
16 </div>
17
18
19 <!-- 子组件模板 -->
20 <template id="cpn">
21 <div>
22 <!-- 遍历子组件中subcategories接收到的数据 -->
23 <button v-for="item in subcategories" @click="btnclick(item)">{{item.name}}</button>
24 <!-- <input v-for="item in subcategories" @click="btnclick(item)" :value="item.name"></input> -->
25 <h2>{{submessage}}</h2>
26 </div>
27
28 </template>
29 <script type="text/javascript" src="../js/vue.js"></script>
30 <script>
31 const cpn = {
32 template: '#cpn',
33 props:{
34 //接收父组件的数据
35 subcategories:{
36 type:Array
37 },
38 submessage:{
39 type:String
40 }
41 },
42 methods: {
43 btnclick(item) {
44 this.$emit('itemclick', item)
45 }//子组件可以使用 $emit 触发父组件的自定义事件
46 }
47 }
48 const vm = new Vue({
49 el: '#app',
50 data: {
51 message: 'hello',
52 categories: [
53 { id: '111', name: '热门推荐' },
54 { id: '222', name: '手机数码' },
55 { id: '333', name: '家用电器' },
56 { id: '444', name: '电脑办公' },
57
58 ]
59 },
60 components: {
61 cpn
62 },
63 computed: {
64
65 },
66 methods: {
67 cpnclick(item) {
68 console.log(item);
69 } //父组件中的自定义事件
70 }
71 });
72 </script>
73 </body>
74
75 </html>