1. 程式人生 > >vue 同級兄弟間數據傳遞

vue 同級兄弟間數據傳遞

觸發 function func tle eth set ctype str bsp

<!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>

vue 同級兄弟間數據傳遞