Vue3组合式API向可组合函数传prop做watch监听不触发如何解决
问题原因分析
你代码的问题出在组件内将prop赋值给ref的逻辑:const pulse = ref(props.barcodePulse)只是提取了props.barcodePulse的初始静态值作为ref的初始值,两者后续没有响应式关联。当父组件修改barcodePulse属性时,props本身是响应式对象,但你本地创建的pulse ref并不会同步更新,因此usePulse内监听pulse的watch回调永远不会触发。
修复方案
使用Vue提供的toRef API创建和prop绑定的响应式ref,两者会保持同步更新,修改组件setup代码即可:
import { defineComponent, ref, toRef } from 'vue' // 记得引入toRef export default defineComponent({ props: { collapseY: { type: Boolean, required: false, default: false }, barcodePulse: { type: Boolean, required: false, default: false } }, setup(props) { // 使用toRef绑定props上的barcodePulse属性,保持响应式关联 const pulse = toRef(props, 'barcodePulse') const {getRandomVerticalScaleValue, getRandomAnimationDuration} = usePulse(pulse) return { getRandomVerticalScaleValue, getRandomAnimationDuration } } })
如果需要同时处理prop上的多个属性,也可以用toRefs批量解构:
const { barcodePulse: pulse, collapseY } = toRefs(props)
额外优化建议
如果你的可组合函数只需要读取pulse的状态不需要修改,也可以直接传入计算属性,和toRef的效果一致:
const pulse = computed(() => props.barcodePulse)
内容的提问来源于stack exchange,提问作者Alessandro Meschi
相关产品推荐
相关产品推荐

