javascript - vue使用v-for渲染列表后如何改变状态?
本文介绍了javascript - vue使用v-for渲染列表后如何改变状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我的目的就是当点击列表的时候,列表改变相应的样式,也就是变为选中状态。
为什么我点击相应列表的时候不会做出响应呢?
但是console.log里面的数据确实改变了,求解!
可以不可以在此基础上解决数据无法响应的问题?
Vue版本: v2.0.3
html:
<div id="app">
<ul class="list-group">
<li v-for="(list, index) in lists" class="list">
<a v-on:click="changeList(index)" v-bind:class="{ active: active[index] }" href="#">{{ active[index] + ' ' + list.title }}</a>
</li>
</ul>
</div>
javascript:
var app = new Vue({
el: '#app',
data: {
lists: [
{title: '标题1'},
{title: '标题2'},
{title: '标题3'},
{title: '标题4'},
{title: '标题5'},
{title: '标题6'},
],
active: [true, false, false, false, false, false]
},
methods: {
changeList: function(index) {
var sideBarList = document.querySelectorAll('.list');
for (let i = 0; i < sideBarList.length; i++) {
if (sideBarList[i] != sideBarList[index]) {
this.active[i] = false;
} else {
this.active[i] = true;
}
}
console.log(this.active);//这里会有变化
}
}
});
css:
ul{
padding: 0;
margin: 0;
width: 300px;
}
.list{
list-style: none;
width: 300px;
}
a{
display: block;
width: 100%;
height: 30px;
line-height: 30px;
text-decoration: none;
background-color: #eee;
}
a:hover, a.active{
background-color: #999;
color: white;
}
解决方案
this.active[i]是不会被检测到的,不会更新dom,要使用this.$set(this.active, i, false)
这篇关于javascript - vue使用v-for渲染列表后如何改变状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文