初始时,activeIndex.value和activeIndex获取到的数值均为0,但是v-show="activeIndex.value === 0"在页面中并未生效,v-show="activeIndex === 0"才生效。点击之后activeIndex变成数组,activeIndex.value获取到的是数字。请根据之前的代码再次进行改写
时间: 2024-04-15 22:28:54 浏览: 131
如何在Vue.js中实现标签页组件详解
非常抱歉之前的回答有误。在Vue 3中,使用`ref`创建的响应式变量需要通过`.value`来访问其值。同时,在判断条件中,应该使用`activeIndex.value`来比较值。
下面是修改后的代码:
```html
<template>
<div>
<ul>
<li v-for="(option, index) in conto" :key="index" :class="{'noww': activeIndex === index}" @click="toggleActive(index)">
{{ option.category_title }}
</li>
</ul>
<div class="cont" v-show="activeIndex === 0">
<ul>
<li v-for="option2 in cont" :key="option2" :class="parseInt(option2.stock) === 1 ? 'olik' : ''">
<a :href="option2.source" target="_blank">
<div class="contimg">
<img :src="option2.bigpic" alt="{{option2.title}}">
</div>
<div class="context">
<span>
<img :src="option2.smallpic" alt="">{{option2.subtitle}}
</span>
<h4><span>{{option2.title}}</span></h4>
<p>{{option2.summary}}</p>
</div>
</a>
</li>
</ul>
</div>
<div class="cont" v-show="activeIndex === 1">
<ul>
<li v-for="option2 in cont2" :key="option2" :class="parseInt(option2.stock) === 1 ? 'olik' : ''">
<a :href="option2.source" target="_blank">
<div class="contimg">
<img :src="option2.bigpic" alt="{{option2.title}}">
</div>
<div class="context">
<span>
<img :src="option2.smallpic" alt="">{{option2.subtitle}}
</span>
<h4><span>{{option2.title}}</span></h4>
<p>{{option2.summary}}
</p>
</div>
</a>
</li>
</ul>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const activeIndex = ref(0);
function toggleActive(index) {
if (activeIndex.value === index) {
activeIndex.value = null;
} else {
activeIndex.value = index;
}
}
return {
activeIndex,
toggleActive,
};
},
};
</script>
```
现在,你可以使用`activeIndex.value`来获取活动索引的值,并根据该值来显示对应的内容。同时,`toggleActive`函数也已经进行了相应的修改。
阅读全文