Vue3 Composition API导出函数传入props参数未响应更新问题求解
问题根因
你调用useDragFunction(props.dragItem)时,直接取出了props对象上dragItem属性的当前值传入组合式函数,这个值本身是普通数组,不具备响应性。后续父组件更新该prop时,组合式函数内持有的还是初始传入的旧值,不会同步更新,因此出现始终拿到空数组的问题。
修复方案
步骤1:传入响应式引用而非原始值
在组件内调用组合式函数前,先通过toRef将props.dragItem包装为响应式Ref对象再传入:
// 组件setup内先从vue导入toRef import { ref, onMounted, toRef } from 'vue' // 原调用useDragFunction的位置调整为 const dragItemRef = toRef(props, 'dragItem') const { dragStart, dragEnd, checkForDragging, isDragging, showPlaceholder} = useDragFunction(dragItemRef)
步骤2:调整组合式函数内的取值逻辑
因为现在传入的是Ref类型对象,取值时需要访问.value属性,同时可新增监听逻辑自动同步状态:
import { ref, watch } from 'vue'; // 入参dragItem为响应式Ref对象 export default function useDragFunction(dragItem){ const isDragging = ref(false) const showPlaceholder = ref(false) function dragStart(){ isDragging.value = true } function dragEnd(){ isDragging.value = false } function checkForDragging(){ // 访问Ref的value属性获取最新值 if (dragItem.value.length > 0){ showPlaceholder.value = true } else { showPlaceholder.value = false } } // 可选优化:自动监听dragItem变化,无需手动触发checkForDragging即可同步showPlaceholder状态 watch(dragItem, () => { checkForDragging() }, { immediate: true }) return{ dragStart, dragEnd, checkForDragging, isDragging, dragItem, showPlaceholder } }
额外说明
如果嫌调整参数麻烦,也可以直接把整个props对象传入useDragFunction,因为props本身是响应式对象,在组合式函数内直接访问props.dragItem也能拿到最新值,但该方案不符合最小暴露原则,会让组合式函数有权限访问所有组件prop,不推荐使用。
另外你组件内onMounted中直接对canDrag、itemName等变量赋值的写法也存在同样的响应性问题,如果对应prop后续会更新,也需要用toRef或者watch做同步处理。
内容的提问来源于stack exchange,提问作者gruen1988
相关产品推荐
相关产品推荐

