vue 同级兄弟间数据传递
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="" id="myVue">
<my-component>
</my-component>
</div>
<!--子组件1-->
<template id="child" >
<div id="">
<div >{{m2}}</div>
</div>
</template>
<!--子组件2-->
<template id="child1" >
<div id="">
<button @click="givedata">传数据到兄弟那</button>
</div>
</template>
<!--父组件-->
<template id="father">
<div>
<mycomponent-child></mycomponent-child>
<mycomponent-child1></mycomponent-child1>
</div>
</template>
</body>
<script type="text/javascript" charset="utf-8">
/* 1.创建事件中心hub
* 2.给组件2加事件'givedata'
* 3.'givedata'事件里面触发hub事件,设置监听事件
* eg:hub.$emit('getdata',this.strr); 'getdata'事件名称,传递的数据this.strr
* 4.组件1的mounted()钩子函数里面用$on监听'getdata'事件,获取数据
* eg:hub.$on('getdata', function (data) {alert(data);})
*/
var hub = new Vue(); //创建事件中心
var child={
template:"#child",
data:function(){
return{
strr:"我是子组件1"
}
},
mounted(){
hub.$on('getdata', function (data) {
alert("子组件1:"+data);
})
}
}
var child1={
template:"#child1",
data:function(){
return{
strr:"我是子组件2的数据"
}
},
methods:{
givedata:function(){
hub.$emit('getdata',this.strr);
}
}
}
/*父组件*/
var father={
template:"#father",
data:function(){
return{
str:"我是父组件"
}
},
components:{
"mycomponentChild":child,
"mycomponentChild1":child1
}
}
vm=new Vue({
//el:"#myVue",
components:{
"myComponent":father
}
}).$mount('#myVue');
</script>
</html>