子向父传值
需要使用自定义事件
子组件
export default{
data(){
return{
count:0
}
},
methods:{
add(){
this.count+=1
this.$emit('numchange',this.count)
}
}
}
父组件
<Son @numchange="getNewCount"></son>
export default{
data(){
return{countFromSon:0}
},
methods:{
getNewCount(val){
this.countFromSon=val
}
}
}
父向子传值
需要使用自定义属性
父组件
<Son :msg='message' :user='userinfo'></Son>
data(){
return{
message:'123456',
userinfo:{name:'www',age:20}
}
}
子组件
<template>
<div>
<p>{{msg}}</p>
<p>{{user}}</p>
</div>
</template>
props:['msg','user']
兄弟组件之间的数据共享
兄弟组件A
import bus form './eventBus.js'
export default{
data(){
return{
msg:'123456',
}
},
methods:{
sendMsg(){
bus.$emit('share',this.msg)
}
}
}
兄弟组件B
import bus form './eventBus.js'
export default{
data(){
return{
msgFromA:'',
}
},
created(){
bus.$on('share',val=>{
this.msgFromA=val
})
}
}
eventBus.js
import Vue from 'vue'
export default new Vue()