vue 非子父组件间的数据传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue 非子父组件间的数据传递</title>
<script src='vue.js'></script>
</head>
<body>
<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)
}
}
}
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指向不变
sub1.$on('runoob1',name=>{
console.log(this)
this.name=name
console.log(name)
})
// 接收runoob2组件中的数据
sub1.$on('runoob2',name=>{
console.log(this)
this.name=name
console.log(name)
})
}
}
var sub=null
window.onload=function(){
sub= new Vue({
el:'#my',
components:{
'my-a':runoob1,
'my-b':runoob2,
'my-c':runoob3,
}
});
}
</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>
<div id='my'>
<my-a></my-a>
<my-b></my-b>
<my-c></my-c>
</div>
</body>
</html>