<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue 非子父組件間的數據傳遞</title>
<script src='vue.js'></script>
</head>
<body>
html
<script>
// 全局組件
// Vue.component('my-hello',{
// template:'<h1>hellow word!</h1>'
// })
var sub1=new Vue();
var runoob1={
data(){
return{
name:'第一個組件'
}
},
template:'#runoob1',
methods:{
send(){
// console.log(11)
sub1.$emit('runoob1',this.name)
}
}vue
}
var runoob2={
data(){
return{
name:'第二個組件'
}
},
template:'#runoob2',
methods:{
send(){
sub1.$emit('runoob2',this.name)
}
}函數
}
var runoob3={
data(){
return{
name:''
}
},
template:'#runoob3',
mounted:function(){
var self=this
// 此時this指向爲上沒空vue實例發生變化 需提早定義好this var self=this
// sub1.$on('runoob1',function(name){
// console.log(this)
// self.name=name
// console.log(name)
// })this
// 箭頭函數this指向不變
sub1.$on('runoob1',name=>{
console.log(this)
this.name=name
console.log(name)
})component
// 接收runoob2組件中的數據
sub1.$on('runoob2',name=>{
console.log(this)
this.name=name
console.log(name)
})
htm
}ip
}it
var sub=null
window.onload=function(){
sub= new Vue({
el:'#my',
components:{
'my-a':runoob1,
'my-b':runoob2,
'my-c':runoob3,
} io
});
}
</script>
<template id='runoob1'>
<div>
<h1>{{name}}</h1>
<button @click='send'>把數據發給runoob3</button>
</div>
</template>
<template id='runoob2'>
<div>
<h1>{{name}}</h1>
<button @click='send'>把數據發給runoob3</button>
</div>
</template>
<template id='runoob3'>
<div>
<h1>{{name}}</h1>
</div>
</template>
console
<div id='my'> <my-a></my-a> <my-b></my-b> <my-c></my-c> </div></body></html>