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

标签 javascript vue.js state vuex

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

我认为这可能是重新渲染问题,因此我尝试了随机子组件键,但这不起作用。我也尝试使用计算 Prop ,但遇到了同样的问题。我觉得我错过了一些简单的东西。

这是控制台中的渲染顺序。最后一次父更新是当 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>    

最佳答案

您的 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 Hook 中执行此操作,它似乎不是正确的位置。我几乎从不需要使用 updated 钩子(Hook)。

关于javascript - VueJS - 在渲染子组件之前等待父组件中的 update(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602046/

相关文章:

php - Laravel 简单文件管理器

haskell - 为什么 StateT 的这个 Applicative 实例可以工作?

javascript - 使用 Re-base 时 Firebase 在 React 中绑定(bind)和解除绑定(bind)

c# - asp.net web 控件的公共(public)属性保存在哪里?

javascript - 使用 jQueryeach 函数来计算具有相同类的 div

javascript - 我应该如何将 Svelte Reactivity 与 DOM getElementById 一起使用?

javascript - 显示: inline is used时隐藏元素符号

javascript - 更改 <img> 上显示的图像的有效方法?

javascript - Vue.js继承调用父方法

javascript - vue 将自定义组件作为属性传递给父组件