- 利用props实现父组件给子组件传递数据,就是子组件可以使用到父组件的数据
<body>
<div id="box">
<father></father>
</div>
<template id="father">
<div>
<p>这是{{msg}}</p>
<son :message="msg"></son>
</div>
</template>
<template id="son">
<p>{{message+'lll'}}</p>
</template>
</body>
<script src="../base/vue.js"></script>
<script>
Vue.component('father',{
template:'#father',
data:function(){
return {
num:20,
msg:'王思懿'
}
},
components:{
son:{
template:'#son',
props:['message'],
}
}
})
new Vue({
el:'#box'
})
</script>
- 通过$emit实现父子组件通信,让父组件可以使用子组件的数据
<body>
<div id="box">
<father></father>
</div>
</body>
<template id="father">
<div>
<p>爸爸在此要说{{newData}}</p>
<son @change='changeData'></son>
</div>
</template>
<template id="son">
<div>
<p>子组件在此</p>
<button @click='speak'>说话</button>
</div>
</template>
<script src="../base/vue.js"></script>
<script>
Vue.component('father',{
template:'#father',
data:function(){
return {
newData:''
}
},
methods:{
changeData(data){
this.newData=data
}
}
})
Vue.component('son',{
template:'#son',
data:function(){
return {
data:'王思懿啦啦啦'
}
},
methods:{
speak:function(){
this.$emit('change',this.data)
}
}
})
new Vue({
el:'#box'
})
- ref实现兄弟之间的通信
<body>
<div id="box">
<bigbrother></bigbrother>
<littlebrother ref='aaa'></littlebrother>
</div>
<template id="bigbrother">
<div>
<p>{{myData}}</p>
<button @click='hit'>哥哥打弟弟</button>
</div>
</template>
<template id="littlebrother">
<div>
<p>{{myData}}</p>
</div>
</template>
</body>
<script src="../base/vue.js"></script>
<script>
Vue.component('bigbrother',{
template:'#bigbrother',
data:function(){
return {
myData:'我是大哥'
}
},
methods:{
hit(){
this.$parent.$refs.aaa.myData='我是弟弟,被打了,呜呜呜'
}
}
})
Vue.component('littlebrother',{
template:'#littlebrother',
data:function(){
return {
myData:'我是小弟,我在笑'
}
}
})
new Vue({
el:'#box'
})
</script>
- eventbus实现兄弟通信
<body>
<div id="box">
<bro></bro>
<di></di>
</div>
<template id="bro">
<div>
<p>我是{{name}}</p>
<button @click='hit'>{{state}}</button>
</div>
</template>
<template id="di">
<div>
<p>我是{{diName}}</p>
<p>我正在{{diState}}</p>
</div>
</template>
</body>
<script src="../base/vue.js"></script>
<script>
let a=new Vue()
Vue.component('bro',{
template:'#bro',
methods:{
hit(){
a.$emit('hitdi')
}
},
data(){
return{
name:'bro',
state:'我要打弟弟了'
}
}
})
Vue.component('di',{
template:'#di',
data(){
return{
diName:'wangyanbin',
diState:'smile'
}
},
methods:{
changeState(){
this.diState='cry'
}
},
mounted(){
a.$on('hitdi',this.changeState)
}
})
new Vue({
el:'#box'
})
</script>