1. 父传子
父页面代码
<sonDialog ref="sonDialog" :fatherMsg="fatherMsg"/>
data() {
return {
fatherMsg:"父消息"
}
子页面代码
props: ['fatherMsg']
使用this.fatherMsg
即可正常取值
2. 子传父
父页面代码
<sonDialog ref="sonDialog" @fatherMethod="fatherMethod"/>
methods: {
fatherMethod(arg1,arg2) {
console.log('这是父页面方法')
}
子页面代码
this.$emit('fatherMethod', arg1, arg2);
使用this.$emit('方法名', 参数1, 参数2,...);
即可调用父方法,可传多个参数
3. 祖传孙
- 可通过1方法,由祖传父,父传子;不推荐
v-bind="$attrs"
:未被声明props
接收的数据会存到$attrs
中
祖页面代码
<fatherDialog ref="fatherDialog " :fatherMsg="fatherMsg" :grandSonMsg="grandSonMsg" />
data() {
return {
fatherMsg:"祖传给父消息(相当于父传子)",
grandSonMsg:"祖传给孙消息"
}
父页面代码
<sonDialog ref="sonDialog" v-bind="$attrs"/>
props: ['fatherMsg'] //只声明接收了fatherMsg
孙页面代码
props: ['grandSonMsg']
孙页面使用this.grandSonMsg
即可正常取值
4. 孙传祖
v-on="$listeners"
祖页面代码
<fatherDialog ref="fatherDialog " @grandFatherMethod="grandFatherMethod"/>
methods: {
grandFatherMethod(arg1) {
console.log('这是祖页面方法')
}
父页面代码
<sonDialog ref="sonDialog" v-on="$listeners"/>
子页面代码
this.$listeners.grandFatherMethod(arg1);
this.$emit('grandFatherMethod',arg1);
上述两个方法都可以调用