1. 父子组件传值
接收父组件传值
props:['name','age']
子传父
触发一个自定义事件
this.$emit('updateName',this.myName)
2. 祖孙组件传值
依赖数据添加,它里面定义的数据,子组件可以选择性注入并直接使用。同时也可以把方法名称
当作数据传进去。
在孙组件中,我们用inject
中接收祖组件传过来的值,跟props
的格式相同(数组)
同时inject
中的值默认页不可以进行更改(默认是只读的),我们需要在data
中中转一下
data() {
return {
name2:'小米',
age2:8
}
}
provide(){
return {
Dovename:this.name2,
Doveage:this.age2,
//方法名当作属性值传入
updataDove:this.updataDove
}
},
我们定义一个provide
方法,这个方法中返回一个对象,把需要传的数据放进去
methods: {
updataDove(data){
this.name2=data.name,
this.age2=data.age
},
}
注:祖级组件中的依赖数据,注意:跟props一样,接过来的数据是只读的,不能修改。
在孙组件中获取 inject:['Dovename','Doveage','updataDove'],
这个时候触发一个点击事件updataDoves
,调用这个方法,把更改过的值传回去,这个时候我们的祖组件的值也可以随时的更新
updataDoves(){
this.myDovename='大米',
this.myDoveage=22,
this.updataDove({name:this.myDovename,age:this.myDoveage})
},
3. 兄弟组件传值
在Vue是原型对象上,添加一个$bus
属性,该属性的的属性值是一个Vue
实例。
将Vue的所有实例,都将共用同一个$bus
。
这个 $bus
属性,我们称之为:中央事件总线
Vue.prototype.$bus = new Vue()
//触发事件
this.$bus.$emit('getAddress',this.address)
//监听事件
this.$bus.$on('getAddress',(e)=>{
this.address = e
})
e 就$emit
传过来的值(this.address)