如何在 Vue 中使 Provide 和 Inject 响应式?
How to make Provide and Inject Reactive in Vue?
我正在尝试使用 provide 和 inject 传递数据,但注入的数据不是反应性的,任何人都可以帮助我使其成为反应性的。
//Parent.vue
<template>
{{ParentName}}
</template>
<script>
export default {
data(){
return{
ParentName: 'Initial Value'
}
}
provide() {
return {
name: this.ParentName,
};
},
}
</script>
我正在使用挂载钩子在 3 秒后更改 'ParentName''
mounted() {
setTimeout(() => {
this.ParentName = "New Name";
}, 3000);
},
在子组件中,我正在注入值
//Child.vue
<template>
{{name}}
</template>
<script>
export default {
inject:['name']
}
</script>
但是我得到的注入名称是 'Initial Value',3 秒后没有得到更新值作为“新名称”。
provide/inject 默认不响应。正如 VUE 文档中所建议的那样,要使 provide 具有反应性,我们必须注意计算的任何变化。在 parent 组件中,您可以执行以下操作:
provide() {
return {
name: computed(() => this.ParentName)
}
然后在 child 中简单地注入它,它应该可以工作。以供参考:
https://v3.vuejs.org/guide/component-provide-inject.html#working-with-reactivity
我正在尝试使用 provide 和 inject 传递数据,但注入的数据不是反应性的,任何人都可以帮助我使其成为反应性的。
//Parent.vue
<template>
{{ParentName}}
</template>
<script>
export default {
data(){
return{
ParentName: 'Initial Value'
}
}
provide() {
return {
name: this.ParentName,
};
},
}
</script>
我正在使用挂载钩子在 3 秒后更改 'ParentName''
mounted() {
setTimeout(() => {
this.ParentName = "New Name";
}, 3000);
},
在子组件中,我正在注入值
//Child.vue
<template>
{{name}}
</template>
<script>
export default {
inject:['name']
}
</script>
但是我得到的注入名称是 'Initial Value',3 秒后没有得到更新值作为“新名称”。
provide/inject 默认不响应。正如 VUE 文档中所建议的那样,要使 provide 具有反应性,我们必须注意计算的任何变化。在 parent 组件中,您可以执行以下操作:
provide() {
return {
name: computed(() => this.ParentName)
}
然后在 child 中简单地注入它,它应该可以工作。以供参考: https://v3.vuejs.org/guide/component-provide-inject.html#working-with-reactivity