Vue3组合式API中监听Prop时Watcher仅触发一次问题排查
Vue3 Props监听失效的问题解决
你遇到的问题根源是直接解构defineProps返回的props会丢失响应性。
在Vue3的<script setup>中,defineProps返回的是一个响应式对象,但如果直接用const { query } = defineProps(...)解构,拿到的query只是一个普通的字符串值,不是响应式引用——它只会保留初始的props值,后续父组件更新query时,这个解构出来的变量不会同步更新,自然watch也不会触发。
解决方法有两种:
方法1:不解构,直接通过props对象访问属性
修改Results.vue的<script setup>部分:
import { defineProps, watch, computed } from "vue"; // 不要解构,直接保留props对象 const props = defineProps({ query: { type: String, default: "", }, }); const queryLength = computed(() => props.query.length); watch( () => props.query, () => { console.debug("Watcher was fired."); }, {immediate: true} ); watch(queryLength, () => { console.debug("Watcher was fired."); });
方法2:用toRefs将解构后的属性转为响应式ref
如果习惯解构写法,可以用toRefs把props对象的属性转为响应式ref:
import { defineProps, watch, computed, toRefs } from "vue"; const props = defineProps({ query: { type: String, default: "", }, }); // 用toRefs解构,得到的query是响应式ref const { query } = toRefs(props); // 计算属性里要访问ref的value const queryLength = computed(() => query.value.length); // 直接监听ref即可 watch( query, () => { console.debug("Watcher was fired."); }, {immediate: true} ); watch(queryLength, () => { console.debug("Watcher was fired."); });
这样修改后,当父组件的query更新时,子组件的watch就能正常触发了,计算属性的监听也会生效。
内容的提问来源于stack exchange,提问作者Mathieu Dhondt
相关产品推荐
相关产品推荐

