我试了又试,但我无法找出问题所在。从我在其他地方可以读到的内容来看,传递给子组件的变量在数据在父组件中可用之前作为 undefined
发送。
引用这里:
<template>
<div id="app">
<child :parentData="data.message"/>
</div>
</template>
<script>
import Child from "./components/Child";
export default {
name: "App",
components: {
Child
},
computed: {
quote() { return 'Better late than never' }
},
data() {
return {
data: { message: this.quote } ,
thisWorks: { message: "You can see this message if you replace what is passed to the child" }
};
}
};
</script>
然后在 child 身上:
<template>
<div>
<h1>I am the Child Component</h1>
<h2> {{ parentData }}</h2>
</div>
</template>
<script>
export default {
name: "Child",
props: {
parentData: { type: String, default: "I don't have parent data" },
},
};
</script>
最佳答案
答案是,您无法访问 this.quote
的值,因为此时 data object
正在创建,computed object
实际上不存在。
这是一个替代方案,我们将使用 created()
生命周期钩子(Hook)来更新 data object
的值:
created(){
this.data = {
message: this.quote
}
},
您不需要更改任何东西,只需添加这行代码就足够了。
我已经在您的 CodeSandbox 项目中测试了这些代码,它的效果非常好。
希望对您有所帮助!
关于vue.js - VueJS 将计算数据作为 Prop 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52518395/