<ul id="onlinecate" class="clearfix"> <li v-for="(option2, index)in conto" v-bind:key="index" :class="classNames[index]" @click="toggleClass(index)">{{option2.category_title}}</li> </ul>const classNames=Vue.ref([]); function toggleClass(index) { this.classNames[index] = this.classNames[index] === 'noww' ? '' : 'noww'; }把以上点击改变class名的代码补充完整,数据不可自定义
时间: 2024-04-13 13:30:50 浏览: 7
根据您提供的代码,以下是完整的点击改变类名的代码:
```html
<template>
<div>
<ul id="onlinecate" class="clearfix">
<li v-for="(option2, index) in conto" :key="index" :class="classNames[index]" @click="toggleClass(index)">
{{ option2.category_title }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
conto: [
{ category_title: 'Category 1' },
{ category_title: 'Category 2' },
{ category_title: 'Category 3' },
],
classNames: [],
};
},
methods: {
toggleClass(index) {
this.$set(this.classNames, index, this.classNames[index] === 'noww' ? '' : 'noww');
},
},
};
</script>
<style>
.noww {
/* 样式定义 */
}
</style>
```
在上面的代码中,`classNames` 是一个响应式数组,用于存储每个选项的类名。初始时,`classNames` 数组为空,没有任何类名。当点击某个选项时,`toggleClass` 方法会切换该选项在 `classNames` 数组中的类名,如果当前类名是 `noww`,则移除该类名;如果当前类名为空,则添加 `noww` 类名。通过使用 `:class` 指令将对应的类名绑定到每个选项上,从而改变样式。在这个示例中,被选中的选项会应用 `noww` 类名。需要注意的是,由于 `classNames` 是一个响应式数组,我们使用 `this.$set` 方法来更新数组的值,以确保界面能够正确地响应数据的变化。