gpt4 book ai didi

javascript - 在 BeforeMount 或 Mounted-VUE.JS 中使用 Prop

转载 作者:行者123 更新时间:2023-12-04 13:24:46 25 4
gpt4 key购买 nike

我在子组件中有 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 thelifecylce 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com