【问题标题】:VueJS - wait for updated() in parent before rendering child componentVueJS - 在渲染子组件之前等待父组件中的更新()
【发布时间】:2020-08-19 11:00:42
【问题描述】:

我以为我已经破解了。我正在尝试从 URL 查询中获取 id,例如http://localhost:8080/car?rec140ttKVWJCDr8v,将其分配给局部变量并将其与存储对象中的 id 进行比较,以提取匹配节点并将其作为道具发送到子组件。除非我在孩子本身触发 webpack 重新渲染,否则它永远不会到达孩子身上。它需要在页面刷新时到达那里。

我认为这可能是重新渲染的问题,所以我尝试了随机子组件键,但没有奏效。我也尝试使用计算道具,但遇到了同样的问题。我觉得我错过了一些简单的东西。

这是控制台中的渲染顺序。最后一次父更新是当汽车对象可用时,但在此之前已经创建并安装了两次子对象。我不知道为什么。

PARENT: created()= [__ob__: Observer]
CHILD: created()= {}
CHILD: mounted()= {}
PARENT: mounted()= [__ob__: Observer]
PARENT: updated()= [__ob__: Observer]
CHILD: created()= {}
CHILD: mounted()= {}
PARENT: updated()= [__ob__: Observer]
PARENT: updated()= (5) [{…}, {…}, {…}, {…}, {…}, __ob__: Observer] //here is when I want the child to render.

这是组件:

// parent
<template>
  <div class="parent">
    // wait for childData to be ready before rendering
    <Child v-bind:data="childData" :key="carId" /> // random keys doesn't work either
  </div>
</template>
<script>
import Child from "@/components/Child";
import { mapState } from "vuex";

export default {
  name: "parent",
  components: {
    Child
  },
  computed: mapState(["carsObject"]), // cars object coming from store, available in updated()
  data() {
    return {
      carId: "",
      childData: {}
    };
  },
  updated() {
    this.childData = this.getCurrentChild();
  },
  methods: {
    getCurrentChild() {
      // get car id from URL
      let ref = location.href;
      let carId = ref.substring(ref.indexOf("?") + 1);
      if (this.carsObject) {
        this.carsObject.forEach(car => {
          if (car.car_id === carId) {
            return car;
          }
        });
      }
    }
  }
};
</script>

// child    
<template>
  <div class="child">
    // do stuff with "data" prop
  </div>
</template>    

【问题讨论】:

  • 你是否使用 VueRouter 进行这样的客户端路由?
  • @Anatoly 不确定您的意思。我正在对一个不是我设计或构建的大型复杂 Vue 应用程序进行一些更新。我只是尽量避免重构太多。
  • 在您的data 中添加一个标志,例如loaded,默认值为false,并在您的childData 加载后将其设置为true。使用它有条件地渲染组件,即&lt;Child v-if="loaded"...

标签: javascript vue.js state vuex


【解决方案1】:

您的 getCurrentChild 方法没有返回任何内容;您的意思是使用find 而不是forEach(假设carsObject 是一个数组)?

getCurrentChild() {
  // get car id from URL
  let ref = location.href;
  let carId = ref.substring(ref.indexOf("?") + 1);
  if (this.carsObject) {
    return this.carsObject.find(car => car.car_id === carId);
  }
}

另外,我不确定您为什么要在 updated 挂钩中这样做,这似乎不是正确的地方。我几乎从不需要使用updated 钩子。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2018-07-23
    • 2019-06-01
    • 2017-04-04
    • 2019-12-31
    • 2021-05-02
    • 2022-12-03
    • 2018-08-12
    • 2019-01-31
    相关资源
    最近更新 更多