我已经尝试过了,但我无法解决问题。从我在其他地方读到的内容来看,传递给子组件的变量会像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>
Run Code Online (Sandbox Code Playgroud)
然后在孩子身上:
<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>
Run Code Online (Sandbox Code Playgroud)
答案是,你无法访问 的值,this.quote因为在创建的那一刻data object,它computed object实际上并不存在。
这是一种替代方案,我们将使用created()生命周期挂钩来更新 的值data object:
created(){
this.data = {
message: this.quote
}
},
Run Code Online (Sandbox Code Playgroud)
您不需要更改任何内容,只需添加这行代码就足够了。
我已经在您的 CodeSandbox 项目中测试了这些代码,它的效果非常好。
希望有帮助!
| 归档时间: |
|
| 查看次数: |
10943 次 |
| 最近记录: |