我在子组件中有 Prop -> kpi_kalite[]
父组件->mounted():
*(这个 kpi_kalite 是在父组件的数据中创建的)
axios.get(URL+ "/KPI/").then(response=>{
console.log(JSON.parse(JSON.stringify(response.data)))
this.kpi_kalite.push(response.data[0])
})
我在父组件中“获取请求”,并将 response.data 推送到 kpi_kalite[](父组件)我将这个数组用于 Prop 。
然后,我想在 beforeMount 或 Mounted 中执行 console.log(this.kpi_kalite)。
但是这个 Prop 在不使用。
methods : {
set_input(){
console.log(this.kpi_kalite)
for(const i in this.kpi_kalite){
console.log(i)
console.log(JSON.parse(JSON.stringify(this.kpi_kalite))) // output
// "undefined"
}
}
},
beforeMount() {
this.set_input()
}
控制台输出:未定义你可以帮帮我吗? ,在加载HTML-css之前,我需要子组件中的父组件数据
最佳答案
有一个post LinusBorg 关于父子生命周期钩子(Hook)的顺序:
There’s nothing weird or wrong about it, it all follows from the lifecylce logically.
- beforeCreate() and created() of the parent run first.
- Then the parent’s template is being rendered, which means the child components get created
- so now the children’s beforeCreate() and created() hooks execute respecitvely.
- these child components mount to DOM elements, which calls their beforeMount() and mounted() hooks
- and only then, after the parent’s template has finished, can the parent be mounted to the DOM, so finally the parent’s beforeMount() and mounted() hooks are called.
END
此外,还有一个很好的图表here .
在挂载父组件之前挂载子组件。因此,
console.log(this.kpi_kalite)
在子组件中不打印从 axios
获取的数据在 parent 。所以,如果你一开始不渲染子组件,它就不会被挂载,因为它没有被创建。如果在 axios 完成后渲染子组件,它会被创建并挂载。然后,console.log
将打印 kpi_kalite
的值来自 axios
在 parent 。父组件 :
<ChildComponent v-if="renderChildComponent" :kpi_kalite="kpi_kalite" />
data() {
return {
kpi_kalite: [],
renderChildComponent: false,
};
},
mounted() {
axios.get(URL+ "/KPI/").then(response=>{
console.log(JSON.parse(JSON.stringify(response.data)))
this.kpi_kalite.push(response.data[0])
this.renderChildComponent = true;
})
},
关于javascript - 在 BeforeMount 或 Mounted-VUE.JS 中使用 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69223699/