props的传递是异步的

 props的传递是异步的

案例如下:

父组件

<template>
  <div class="approvals-container">
   
    <Son :id="num" ref="refSon" />
    <button @click="changeID">修改id</button>

  </div>
</template>
<script>
import Son from './son'
export default {
  components: { Son },
  data() {
    return {
      num: 1
    }
  },
  methods: {
    changeID() {
      this.num = 2
      console.log(this.$refs.refSon.id) // 通过 ref 的引用方式拿到子组件的 id值看看是多少 
      this.$refs.refSon.doSomething()   // 假如发送ajax
    
    }
  }
}
</script>

子组件

<template>
  <div>
    props:{{ id }}
  </div>
</template>
<script>
export default {
  props: {
    id: {
      type: Number,
      required: true
    }
  },
  methods: {
    doSomething() {
      console.log('发ajax', this.id)
    }
  }
}
</script>

当我们点击父组件的修改 修改id 按钮 时,

1. 修改 num 的值,并传给子组件的 id 属性

2. 通过 ref 的引用方式拿到子组件的 id值看看是多少 

3. 假如我们发ajax

结果如下:

修改 id前:

可以看到子组件中的 props 的 id 值是 1

 修改 id 后

 点击修改 id 后可以看到

通过 ref 的引用方式拿到子组件的 id值和ajax 的值还是1 

但是插槽的 id 值却是2

解决方法

父组件的   this.$refs.refSon.doSomething()

用  this.$nextTick(() => { } 包裹起来,这样就解决了问题

 this.$nextTick(()=>{ })  解释如下: 

 this.$nextTick(()=>{ }) 将回调函数中的操作放到下一次DOM更新之后执行,类似全局方法vue.nextTick,只不过 this.$nextTick 只作用于调用它的实例

<template>
  <div class="approvals-container">
   
    <Son :id="num" ref="refSon" />
    <button @click="changeID">修改id</button>

  </div>
</template>
<script>
import Son from './son'
export default {
  components: { Son },
  data() {
    return {
      num: 1
    }
  },
  methods: {
    changeID() {
      this.num = 2
       this.$nextTick(() => {
      this.$refs.refSon.doSomething()
      console.log(this.$refs.refSon.id) 
       })
    }
  }
}
</script>

结果如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值