【问题标题】:What is the correct way to change the data of an already mounted component?更改已安装组件的数据的正确方法是什么?
【发布时间】:2020-08-09 03:08:35
【问题描述】:

我正在学习 vue2 并遇到了这种情况。我渲染了一个包含项目列表的组件,当我单击这些项目中的任何一个时,会显示另一个组件以及项目的详细信息。当在 created 钩子中创建明细组件时,我调用了一个 api 来获取明细数据。到现在为止还挺好。我的问题是单击另一个项目后,详细信息不会更改其数据。我理解这是因为创建的钩子没有被再次调用。

我尝试了updatedbeforeUpdate 钩子,但在这两种情况下我都遇到了不好的行为,我猜这是因为它们调用了相同的fetchDetail 方法。我认为的另一个解决方案是,在将新选定项中的 selectedItem 状态属性传递给它之前,将其传递一个空值 {} 以使组件被渲染。但没有成功

来自父组件的数据

data {
  selectedItem: {}
}

父组件中的方法

displayDetailHandler({ id, title }) {
  this.selectedItem = {}; // intro provocar rerender
  this.selectedItem = { id, title };
}

调用子组件

<template v-if="Object.keys(selectedItem).length > 0">
  <Detail :item="selectedItem"></Detail>
</template>

子组件created钩子

created() {
  this.fetchGameDays(); // call to api
}

更改已安装组件的数据的正确方法是什么?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    在不断变化的prop 上使用watch(在您的情况下,在itemid 上):

    watch: {
      'item.id': {
        handler(id) {
          if (id) {
            // call API, using the id
          }
        },
        immediate: true /* makes it run immediately after you set the watcher,
                         * does not wait until first change (like `created` call) */
      }
    }
    

    此外,您可能希望在子组件关闭时nullify 子数据,因此当您第二次打开它时,它不会在新的 API 调用正在获取时显示旧数据。

    附带说明,v-if="Object.keys(selectedItem).length &gt; 0" 可以简化为
    v-if="selectedItem.id"

    【讨论】:

    • 感谢您的示例。和建议
    【解决方案2】:

    你可以在 vuejs 中使用watch 它基本上是一个函数,每次对正在监视的数据进行更改时都会调用该函数。因此,有时如果您正在观看一个复杂的对象,那么您可能需要在 watch 属性中使用 deep:true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2012-10-16
      • 2015-04-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 2020-11-22
      相关资源
      最近更新 更多