vue 数据监听

如图:

clipboard.png

两列表用来两个list数组装,当我点击添加时下面的那一条数据添加到上面的list数组中,同时这一条的背景色改变,两个列表都是用v-for循环出来的。
想实现添加一条数据上去背景色就改变。

阅读 3.1k
3 个回答

如果要比较好一点控制的话,可以加一个属性,用来控制背景色

//先帮数组加个active
this.list.forEach(l=>{
    l.check=false
})

//在循环里面控制样式

<div v-for="(item,index) in list" :class="{active:item.active}"></div>
.active{
    background-color:green;
}


//新增元素
//如果有别的active:true,先置为false
this.list.forEach(l=>{
    if(l.active) l.active=false
})
this.list.push({
    ...
    active:true
})

你是先想要监听list数组的变化,并响应渲染,但并没有效果?
贴出你的代码来看看问题在哪里。有可能是跟vue的组件渲染生命周期有关。

是最后一条数据添加背景色吗?
1.最简单的方法用css的:last-child选择器

 li:last-child{
    background: green;
    }

2.v-for循环判断添加active:class="index+1==items.length?'active':''"

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>        
        <style type="text/css">
            ul{
                list-style: none;
            }
            li.active{
                background: green;
            }
            li:last-child{
                background: green;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <ul>
                <li v-for="(item,index) in items" :key="index" :class="index+1==items.length?'active':''">{{item}}</li>
            </ul>
            <button @click="add">添加</button>
        </div>
        
        <script src="vue.js"></script>
        <script>
            var vm = new  Vue({
                el:"#box",
                data:{
                    items:["aaa","bbb","ccc"]
                },
                methods:{
                    add:function(){
                        this.items.push("ddd");
                    }
                }
            })
        </script>
    </body>
</html>

3.调用函数返回class

<li v-for="(item,index) in items" :key="index" :class="addactive(index)">{{item}}</li>
methods:{
                    add:function(){
                        this.items.push("ddd");
                    },
                    addactive:function(index){
                        if(index==this.items.length){
                            return 'active';
                        }
                    }
                }

当然还有其他方法,就不多说了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题