【问题标题】:How to get updated prop from parent after forcing a method call in Vue js?在 Vue js 中强制方法调用后如何从父级获取更新的道具?
【发布时间】:2020-11-24 14:11:18
【问题描述】:

我有一个事件发射器,它强制在父级中调用 API:

父组件

<ProductChild
        :productId="productId"
        @update="getProduct()"
        :product="product"
       
      ></ProductChild>

子组件

 props: {
    product: {
      type: Object,
    },
    }

methods: {
updateProductTag(){
 this.$emit('update')
arait this.productItem = this.product
}
}

似乎孩子强制在 Parent 中调用 api,但我没有在孩子中获得更新的道具。出了什么问题,如何通过强制在父级中调用该方法也传递新道具并在子级中使用更新后的道具?

【问题讨论】:

  • 如果getProduct 没有改变传递给孩子的道具之一,那么孩子中就不会有新数据。您没有展示该方法,所以我们不知道它的作用。

标签: vue.js vuejs2 vue-component


【解决方案1】:

您需要注意道具。不保证发出后您会立即获得更改。

 props: {
    reportId: {
      type: Number,
    },
    product: {
      type: Object,
    },
},
watch:{
  product(){
    this.productItem = this.product
    // after product has updated
  }
},

methods: {
 updateProductTag(){
   this.$emit('update')
  // arait this.productItem = this.product
 }
}

最好在子组件中执行“getProduct()”,然后通过以下方式将结果传递给父组件:

this.$emit('update:product', theResultOfGetProduct)

并通过同步在父级中捕获它:

<ProductChild
  :productId="productId"
  :product.sync="product"       
></ProductChild>

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 2021-07-31
    • 2019-05-02
    • 2018-01-10
    • 2019-06-08
    • 2018-05-27
    • 1970-01-01
    • 2015-12-07
    • 2021-10-03
    相关资源
    最近更新 更多