Vue.js 中为 li 元素添加属性 - 完整指南
<template>
<ul>
<li v-for='(item, index) in items' :key='index' :class='{ active: index === currentIndex }' @click='setCurrentIndex(index)'>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
currentIndex: 0
}
},
methods: {
setCurrentIndex(index) {
this.currentIndex = index
}
}
}
</script>
<p>在上面的示例中,我们使用 :class 指令将 'active' 类添加到当前 li 元素,只有当 index 等于 currentIndex 时才会添加。我们还使用 @click 指令将 setCurrentIndex 方法绑定到点击事件上,这将更新 currentIndex 的值并更新列表项的类。</p>
原文地址: https://www.cveoy.top/t/topic/mNJq 著作权归作者所有。请勿转载和采集!