我正在构建一个使用 Vue 3 的应用程序,并且在父组件中提供一个属性,随后将其注入到多个子组件中。有什么方法可以让注入此属性的组件观察它的变化吗?
父组件看起来像:
<template>
<child-component/>
<other-child-component @client-update="update_client" />
</template>
<script>
export default {
name: 'App',
data() {
return {
client: {}
}
},
methods: {
update_client(client) {
this.client = client
}
},
provide() {
return {
client: this.client
}
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
子组件如下所示:
<script>
export default {
name: 'ChildComponent',
inject: ['client'],
watch: {
client(new_client, old_client) {
console.log('new client: ', new_client);
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
我试图实现这一点:当提供的变量在父级中更新时,注入该变量的子组件应该得到通知。由于某种原因,当客户端更新时,客户端监视方法不会被调用。
有更好的方法来实现这一点吗?
更新
经过进一步测试,我发现这里存在一个更大的问题,即使在父组件中更新了客户端后,子组件中的客户端属性仍然是原始的空对象并且不会更新。由于提供的属性是反应性的,所以它注入的所有位置都应该自动更新。
如何从子模块中访问父/调用模块的名称。
或者,如何从子模块中获取调用模块的文件名?
例如
module "test_parent_module" {
source = "./child_module"
}
Run Code Online (Sandbox Code Playgroud)
module "child_module" {
locals {
// What could I use here to get parent module name?
parent_module_name = module.parent # Should output "test_parent_module"
// What could I use here to get the parent module's file name?
parent_file_name = module.parent.filename # Should output "test_parent_module.tf"
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢