vue 祖父孙传值

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);

上述两个方法都可以调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值