<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>非父子元件間的通訊</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!-- A元件和 B元件向C元件傳送資料 ,在C元件裡負責訂閱 監聽 ,A, B元件負責傳送 $emit-->
<div id="app">
<my-a></my-a>
<my-b></my-b>
<my-c></my-c>
</div>
<template id="a">
<div>
A元件:{{name}}
<button type="button" @click="send">將資料傳送給C元件</button>
</div>
</template>
<template id="b">
<div>
B元件:{{age}}
<button type="button" @click="send">將資料傳送給C元件</button>
</div>
</template>
<template id="c">
<div>
<h3>C元件:
{{name1}},{{age}}
</h3>
</div>
</template>
<script>
var Event = new Vue();
var A={
template:'#a',
data(){
return {
name:'tom'
}
},
methods:{
send(){
Event.$emit('data-a',this.name)
}
}
}
var B={
template:'#b',
data(){
return {
age:20
}
},
methods:{
send(){
Event.$emit('data-b',this.age)
}
}
}
var C={
template:'#c',
data(){
return {
name1:'',
age:''
}
},
mounted(){
Event.$on('data-a',name=>{
this.name1 = name
})
Event.$on('data-b',age=>{
this.age = age
})
}
}
var vm=new Vue({
el:'#app',
components:{
'my-a':A,
'my-b':B,
'my-c':C
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>非父子元件間的通訊</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!-- A元件和 B元件向C元件傳送資料 ,在C元件裡負責訂閱 監聽 ,A, B元件負責傳送 $emit-->
<div id="app">
<my-a></my-a>
<my-b></my-b>
<my-c></my-c>
</div>
<template id="a">
<div>
A元件:{{name}}
<button type="button" @click="send">將資料傳送給C元件</button>
</div>
</template>
<template id="b">
<div>
B元件:{{age}}
<button type="button" @click="send">將資料傳送給C元件</button>
</div>
</template>
<template id="c">
<div>
<h3>C元件:
{{name1}},{{age}}
</h3>
</div>
</template>
<script>
var A={
template:'#a',
data(){
return {
name:'tom'
}
},
methods:{
send(){
vm.$emit('data-a',this.name)
}
}
}
var B={
template:'#b',
data(){
return {
age:20
}
},
methods:{
send(){
vm.$emit('data-b',this.age)
}
}
}
var C={
template:'#c',
data(){
return {
name1:'',
age:''
}
},
mounted(){
this.$nextTick(()=>{
console.log(vm);
vm.$on('data-a',name=>{
this.name1 = name
})
vm.$on('data-b',age=>{
this.age = age
})
})
}
}
var vm=new Vue({
el:'#app',
components:{
'my-a':A,
'my-b':B,
'my-c':C
}
});
</script>
</body>
</html>