VueJS-在渲染子组件之前等待父组件中的updated()

时间:2020-05-04 21:35:32

标签: javascript vue.js state vuex

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

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

这是控制台中的渲染顺序。最后一个父级更新是在carsObject可用时,但是在此之前已经创建了子级并将其挂载了两次。我不确定为什么。

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>    

1 个答案:

答案 0 :(得分: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钩子。