使用Composition API时ref()变量重新赋值无响应问题排查
轮播组件Composition API响应式更新失效问题
问题场景
以下是一个简单的轮播组件模板:
<template> <div ref="wrapperRef" class="js-carousel container"> <div class="row"> <slot></slot> </div> <div class="row"> <template v-for="n in noOfSlides" :key="n"> <span style="margin-right: 25px;" @click="console.log(n)">O</span> </template> </div> </div> </template>
使用Options API时组件可正常工作:挂载后noOfSlides能正确更新,循环渲染也会重新执行
export default { name: 'carousel', data() { return { noOfSlides: 0 } }, mounted(){ this.noOfSlides = this.$refs.wrapperRef.querySelectorAll('.js-carousel-item').length; } }
但使用如下Composition API写法时无法正常工作:noOfSlides未更新,导致循环不重新渲染
export default { name: 'carousel', setup() { const wrapperRef = ref(null); let noOfSlides = ref(0); onMounted(function () { noOfSlides = wrapperRef.value.querySelectorAll('.js-carousel-item').length;// 此处能正确获取到轮播项数量(大于0) }) return { wrapperRef, noOfSlides } } }
请问忽略了什么问题?
问题原因与修复方案
核心问题
你在onMounted钩子中直接覆盖了noOfSlides这个ref响应式对象,而非修改它的.value属性。
Vue中ref()创建的响应式变量,必须通过.value访问和修改其内部值。你的代码将noOfSlides重新赋值为普通数字,彻底破坏了它的响应式引用,导致模板无法感知数值变化。
修复后的代码
export default { name: 'carousel', setup() { const wrapperRef = ref(null); let noOfSlides = ref(0); onMounted(function () { // 改为更新ref的value属性 noOfSlides.value = wrapperRef.value.querySelectorAll('.js-carousel-item').length; }) return { wrapperRef, noOfSlides } } }
补充说明
- Options API中
this.noOfSlides的赋值操作,Vue内部已自动处理响应式更新逻辑; - Composition API的
ref变量必须显式通过.value操作,读取和修改均需遵循此规则。
内容的提问来源于stack exchange,提问作者Beingnin
相关产品推荐
相关产品推荐

