
在 Vue 3 模板中调用带参数的函数时,需注意 ref 会被自动解包(unwrapped),导致传入的是原始值而非响应式引用,从而引发 Cannot assign to property 'value' 错误。正确做法是避免在模板中直接传递 ref,改用计算属性 + 索引管理或闭包封装。
在 vue 3 模板中调用带参数的函数时,需注意 `ref` 会被自动解包(unwrapped),导致传入的是原始值而非响应式引用,从而引发 `cannot assign to property 'value'` 错误。正确做法是避免在模板中直接传递 `ref`,改用计算属性 + 索引管理或闭包封装。
Vue 3 的模板表达式会对 ref 进行自动解包(auto-unwrapping):当你在 @click 中写 nextType(clothingTypes, selectedClothingType) 时,Vue 不会传入 ref 对象本身,而是将其 .value(即字符串 'blazerAndShirt')作为第二个参数传入。因此函数体内执行 refVariable.value = ... 实际等价于 'blazerAndShirt'.value = ... —— 这在 JavaScript 中非法,自然抛出 TypeError。
✅ 正确且推荐的解决方案是分离状态与逻辑:用 ref 管理索引(而非直接存储值),再通过 computed 衍生当前项。这种方式更符合 Vue 的响应式设计哲学,也避免了模板中复杂的函数调用和参数传递:
import { ref, computed } from 'vue'
const clothingTypes = ['blazerAndShirt', 'blazerAndSweater', 'collarAndSweater', 'graphicShirt']
const currentItemIndex = ref(0) // ✅ 存储数字索引,非字符串值
// ✅ 自动响应索引变化,安全高效
const currentItem = computed(() => clothingTypes[currentItemIndex.value])
// ✅ 模板中直接调用,无需传参
function nextItem() {
currentItemIndex.value = (currentItemIndex.value + 1) % clothingTypes.length
}
function prevItem() {
currentItemIndex.value = (currentItemIndex.value - 1 + clothingTypes.length) % clothingTypes.length
}
模板中使用简洁明了:
<button>Next</button>
<button>Prev</button>
<p>Current: {{ currentItem }}</p>
⚠️ 注意事项:
vue-composition-api-best-practices
Vue 3 组合式 API 与
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
最新文章
