本篇文章给大家带来的内容是关于基于vue双向绑定实现的动态列表+动态样式(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
先上效果图
注:下面的几个值可以从其他地方获取,这边演示我是写死的
在上逻辑图
接着上代码
template部分
选择的选项:
{{item}}
//choose事件绑定写在最外层应用的js的事件委托,如果有不知道的可以参考我的一篇关于事件委托的文章
{{item.label}}
script部分
export default {
name: 'HelloWorld',
data() {
return {
selectlistlabel:[], //用来展示是选项
selectlistvalue:[], //展示选项的值
list: [ //实际当中这部分数据为后台获取,现在为了方便写几个演示用
{value: 'New York',label: 'New York'},
{value: 'London',label: 'London'},
{value: 'Sydney',label: 'Sydney'},
{value: 'Ottawa',label: 'Ottawa'},
{value: 'Paris',label: 'Paris'},
{value: 'Canberra',label: 'Canberra'}
],
}
},
computed:{
activeclass: function() {
return 'active'
},
},
methods:{
choose:function(e){
let dom = e.target;
//获取绑定在dom上的数据
var domvalue = dom.getAttribute("value");
var domlabel = dom.getAttribute("label");
//如果点到空白地方
if(dom.getAttribute("label") == null){
return;
}
//如果点击的对象的值已经在数组里面了,则把他从数组中删除
//否则就把他添加到数组里面去
if(dom.getAttribute("class") == "active"){
for(let i = 0;i
if(this.selectlistvalue[i] == domvalue){
this.selectlistvalue.splice(i,1)
}
}
for(let i = 0;i
if(this.selectlistlabel[i] == domlabel){
this.selectlistlabel.splice(i,1)
}
}
}else{
this.selectlistvalue.push(domvalue)
this.selectlistlabel.push(domlabel)
}
},
}
}
style部分
.active{
background-color: #0ccfbf;
color: white;
}
注:详细说明标注代码上了,
需要注意的坑:1.activeclass需要在computed里面把他return出来,否则加载不到样式。
2.对数组的操作方法,简单点使用vue支持的变异方法(否则vue无法检测到数组变化,也就无法动态绑定)
官网截了一小段图
相关推荐: