Vue中ref未生成响应式属性:如何让betterDog.name实现响应式?
Vue子组件ref属性未随父组件props响应式更新问题
父组件TestPage.vue通过props向子组件TestChild.vue传递parentDog对象,初始状态下父组件的parentDog.name与子组件的betterDog.name一致。点击父组件绿色按钮修改parentDog.name后,父组件数据已更新,子组件的dog prop同步变化,但子组件中用ref定义的betterDog.name未响应式更新,页面无变化。现寻求无需watch监听dog prop的方案,让betterDog.name实现响应式。
父组件 TestPage.vue
<template> <div> <TestChild :dog="parentDog" /> <div v-on:click="changeName" id="change-button"> 修改父组件狗名 </div> </div> </template> <script> import TestChild from "@/test/TestChild"; export default { components: { TestChild }, methods: { changeName() { this.parentDog.name = "已修改的狗名"; alert("修改完成!"); } }, data() { return { parentDog: { name: "初始狗名" } }; }, }; </script> <style> #change-button { margin: 2em; padding: 1em; background-color: green; } </style>
子组件 TestChild.vue
<template> <div>{{ betterDog.name }}</div> </template> <script> import { ref } from 'vue'; export default { name: "TestChild", props: { dog: Object }, data() { return { betterDog: Object }; }, created() { this.betterDog = {}; this.betterDog.name = ref(this.dog.name); } }; </script>
无需watch的解决方案
方案1:使用计算属性(推荐)
直接通过计算属性返回依赖于props的结果,天然具备响应式特性,无需额外维护状态:
<template> <div>{{ betterDog.name }}</div> </template> <script> export default { name: "TestChild", props: { dog: Object }, computed: { betterDog() { return { name: this.dog.name // 可在此扩展betterDog的其他属性 }; } } }; </script>
方案2:使用toRef关联props属性
利用Vue的toRef方法,将props中的dog.name转换为响应式引用,保持与原props的关联:
<template> <div>{{ betterDog.name }}</div> </template> <script> import { toRef } from 'vue'; export default { name: "TestChild", props: { dog: Object }, data() { return { betterDog: {} }; }, created() { this.betterDog.name = toRef(this.dog, 'name'); } }; </script>
注:Vue模板会自动解包ref,因此无需在模板中添加.value。
方案3:让betterDog成为响应式对象并关联props
通过reactive创建响应式对象,直接关联父组件传递的props:
<template> <div>{{ betterDog.name }}</div> </template> <script> import { reactive } from 'vue'; export default { name: "TestChild", props: { dog: Object }, data() { return { betterDog: reactive(this.dog) }; } }; </script>
内容的提问来源于stack exchange,提问作者parsecer
相关产品推荐
相关产品推荐

