vue 平行组件传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue 平行组件传值</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="https://mirrors.idiyrom.com/web/js/vue.mini.js"></script>
<script>
let bus = new Vue();
// Test ==> Test2传值 Test2要声明事件 $on("事件的名字", function(val) { })
// Test要触发事件 $emit("Test2要声明事件名", 需要传值)
// 前提这两个方法必须绑定到同一实例化对象上(bus)
Vue.component("Test2", {
data() {
return {
text: ""
}
},
template: `
<div class="test2">
<h2>{{ text }}</h2>
</div>`,
methods: {

},
created() {
//箭头函数中this指的谁调用此函数父级对象
//es6 function函数,谁调用this就指向谁
bus.$on("testData", (val) => {
this.text = val;
});
}
});

Vue.component("Test", {
data() {
return {
msg: "我是子组件的数据"
}
},
template: `
<div class="test">
<button @click="clickHandler">传递</button>
</div>`,
methods: {
clickHandler() {
// console.log(this.msg);
bus.$emit("testData", this.msg);
}
}
});
let vHeader = {
data() {
return {

}
},
template: `
<div class="header">
<Test></Test>
<Test2></Test2>
</div>`
};

let App = {
data() {
return {

}
},
template: `
<div class="app">
<vHeader></vHeader>
</div>`,
components: {
vHeader
}
};

new Vue({
el: "#app",
data() {
return {

}
},
components: {
App
}
});

</script>
</body>
</html>