使用<script setup>
语法时,Vue模板在渲染期间会尝试访问响应式变量和函数。当您遇到类似的警告消息“Property 'selectedItemIndex' was accessed during render but is not defined on instance.”时,这通常是由于在<script setup>
部分未正确导入或定义相应的变量。
请确保按照以下步骤检查和修复此问题:
- 在
<script setup>
部分使用ref
函数来定义响应式变量,并通过解构赋值从返回的引用对象中获取变量。
<script setup>
import { ref } from 'vue';
const selectedItemIndex = ref(-1); // 使用ref定义响应式变量
const items = [/* your item data */]; // 你的选项数据
// ...其它代码
</script>
- 确保在模板中正确访问响应式变量。在模板中,使用
.value
来访问ref
包装的响应式变量。
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
:class="{ active: index === selectedItemIndex.value }" <!-- 使用 .value 访问变量 -->
@click="selectItem(index)"
>
{{ item }}
</li>
</ul>
</template>
- 检查
selectItem
函数是否在正确的位置,并确保它能够访问到selectedItemIndex
变量。
<script setup>
// 先导入需要的模块和函数
// 确保 `selectedItemIndex` 变量在这之前定义
const selectedItemIndex = ref(-1);
const items = [/* your item data */];
// 定义 `selectItem` 函数并确保它能够访问到 `selectedItemIndex` 变量
const selectItem = (index) => {
selectedItemIndex.value = index;
};
</script>
通过检查上述步骤,您可以解决警告消息“Property 'selectedItemIndex' was accessed during render but is not defined on instance.”。确保正确定义和访问响应式变量,并将其绑定到模板中以供渲染使用。