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

标签 javascript vue.js lifecycle vue-props

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

相关文章:

JavaScript 每 4 秒运行一次函数多次

javascript - 更改插件以使用 on() 事件绑定(bind)

javascript - 检测 JavaScript 中的组合击键

vue.js - 如何动态设置 v-select 值?

javascript - 使用jQuery将元素移动到倒数第二个h2之前

javascript - 我想删除除 "."之外的所有非数字和所有标点符号

css - 如何使表格标题不可滚动bootstrap vue

iOS swift : Best practices for starting app with an alternative UIViewController

ios - 关闭 View 后如何手动调用 ViewDidAppear?

java - Log4j 记录器的生命周期及其使用的资源