我在 Vue 中有一个字符串列表,我使用 v-for
通过 Bootstrap 在“list-group”中列出所有这些字符串。我想在单击其中一个项目时设置“事件”状态,但我找不到使用 for 循环来标识列表中特定项目的方法。
HTML -
<div class="list-group" id="ServersList">
<a href="#" class="list-group-item" v-for="Server in Servers">{{Server.text}}</a>
</div>
VueJS -
var ServersList = new Vue({
el: '#ServersList',
data: {
Servers: [
{ text: '1' },
{ text: '2' },
{ text: '3' },
{ text: '4' },
{ text: '5' },
{ text: '6' }
})
最佳答案
您可以在服务器中使用v-for="(Server, index)"
。 Index 将存储每个元素的当前索引。这样您就可以像这样调用定义的方法:
在您的 View 模型定义中添加以下内容:
data: {
currentIndex: 0
},
methods: {
myClick(index) {
this.currentIndex = index
}
}
修改模板中的 a 标签:
<a href="#"
v-for="(server, index) in Servers"
:class="{yourActiveClass: currentIndex === index, yourInactiveClass: currentIndex !== index}"
@click="myClick(index)">
关于javascript - 使用 Vue JS 和 for 循环设置事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274942/