【发布时间】: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。使用它有条件地渲染组件,即<Child v-if="loaded"...
标签: javascript vue.js state vuex