我有一个这样的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
的组件。
现在在我的Form Builder组件中:
<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标记中,但是当我在安装的部分中console.log this.form.id
时,它没有定义!!
有人可以帮我弄这个吗?为什么它是未定义的?
答案 0 :(得分:0)
由于组件的生命周期,这是预期的行为,子组件在form.id
可用之前就已挂载,挂接的钩子执行一次,但是模板在form.id
时将重新呈现可用,要在脚本中使用此道具,应将其与computed
或watch
选项一起使用:
<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>