代码之家  ›  专栏  ›  技术社区  ›  Mario

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

  •  1
  • Mario  · 技术社区  · 5 年前

    我试过了 updated , beforeUpdate 但在这两种情况下,我都会有一种不好的行为,我想是因为它们调用相同 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
    }
    

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

    2 回复  |  直到 5 年前
        1
  •  1
  •   tao    5 年前

    watch prop (在你的情况下 item id ):

    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) */
      }
    }
    

    null 当子组件关闭时通知子数据,这样当您第二次打开它时,它不会在新的API调用获取时显示旧数据。

    作为旁注, v-if="Object.keys(selectedItem).length > 0" 可以简化为
    v-if="selectedItem.id"

        2
  •  1
  •   Singh    5 年前

    你可以用 watch 它基本上是一个函数,每次被监视的数据发生变化时都会被调用。所以有时候,如果你正在观察的是一个复杂的对象,那么你可能需要使用深:真的手表的属性。

    推荐文章