【问题标题】:cant access to props in mounted无法访问已安装的道具
【发布时间】:2020-11-12 06:41:43
【问题描述】:

我有一个像这样的 vue 组件:

<template>
    <div>
        <div class="page-head">
            <h4 class="mt-2 mb-2"> {{form.name}} </h4>
        </div>
        <form-builder :form="form"></form-builder>

    </div>
</template>

<script>

import FormBuilder from './FormBuilder.vue';

export default {
    data(){
        return {
            form : {}
        }
    },
    components : {
        'form-builder' : FormBuilder
    },
    mounted : function () {
        let formUid = this.$route.params.uid;
        axios.get(`/api/form/uid/${formUid}`).then(res => {
            this.form = res.data;
        });
    }
}
</script>

<style scoped>
</style>

如您所见,该组件从数据库中获取一个表单实例并将其传递给另一个名为 FormBuilder 的组件。
现在在我的表单生成器组件中,我有:

<template>
    <div>
        <h3> Test : {{form.id}} </h3>
    </div>
</template>

<script>
export default {
    props : ['form'],
    mounted : function () {
        console.log(this.form.id); // !!! this.form.id is undefined!
    }
}
</script>

<style scoped>
</style>

当我运行代码时,我可以看到form.id 成功显示在h3 标记中,但是当我在mounted 部分控制台.log this.form.id 时它给了我未定义!!! 有人可以帮我弄这个吗?为什么它是未定义的?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    这是由于组件生命周期的预期行为,子组件在form.id可用之前挂载,挂载的钩子执行一次但当form.id可用时模板将重新渲染,以在你的脚本中使用这个道具,你应该将它与computedwatch 选项一起使用,例如:

    <template>
        <div>
            <h3> Test : {{form.id}} </h3>
        </div>
    </template>
    
    <script>
    export default {
        props : ['form'],
        watch:{
           form(newVal,oldVal){
                console.log('watch : ',this.form.id)  //if you check the console you'll see
                                                      // watch : undefined
                                                       // watch : "your value" 
            }
        }, 
        mounted : function () {
            console.log(this.form.id); // !!! this.form.id is undefined!
        }
    }
    </script>
    
    <style scoped>
    </style>
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多