Vue3带参数调用函数的正确语法及TypeError报错解决
问题原因
Vue模板中直接使用ref变量时会自动解包,你传递给nextType的selectedClothingType其实是它的value值(字符串),而非ref对象本身。函数里尝试给字符串的value属性赋值,自然触发类型错误。
解决方法
方法一:直接使用作用域内变量(推荐)
由于nextType和clothingTypes、selectedClothingType处于同一作用域,无需传递参数,既简化代码又避免解包问题:
修改函数:
const nextType = () => { const currentIndex = clothingTypes.indexOf(selectedClothingType.value); const nextIndex = (currentIndex + 1) % clothingTypes.length; selectedClothingType.value = clothingTypes[nextIndex]; };
模板调用:
@click="nextType"
方法二:传递ref对象(不推荐,冗余)
如果一定要通过参数传递ref对象,需避免Vue自动解包,可将ref放入reactive对象中:
修改变量定义:
const clothingTypes = ['blazerAndShirt', 'blazerAndSweater', 'collarAndSweater', 'graphicShirt']; const state = reactive({ selectedClothingType: ref(clothingTypes[0]) });
函数保持不变:
const nextType = (array, refVariable) => { const currentIndex = array.indexOf(refVariable.value); const nextIndex = (currentIndex + 1) % array.length; refVariable.value = array[nextIndex]; };
模板调用:
@click="nextType(clothingTypes, state.selectedClothingType)"
内容的提问来源于stack exchange,提问作者guguga
相关产品推荐
相关产品推荐

