先上效果圖vue
注:下面的幾個值能夠從其餘地方獲取,這邊演示我是寫死的數組
在上邏輯圖dom
接着上代碼
template部分this
<template> <div > <div> <span>選擇的選項:</span> <span v-for="item in selectlistlabel" style="margin-left: 10px;">{{item}}</span> </div> //choose事件綁定寫在最外層應用的js的事件委託,若是有不知道的能夠參考個人一篇關於事件委託的文章 <div @click="choose" v-for="item in list"> <div v-bind:class="[selectlistvalue.indexOf(item.value)>-1?activeclass:'']" :label="item.label" :value="item.value" style="margin: 5px auto;width: 100px;height: 38px;border:1px solid #e9eaec;line-height: 38px;border-radius: 5px;"> {{item.label}} </div> </div> </div> </template>
script部分spa
<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<this.selectlistvalue.length;i++){ if(this.selectlistvalue[i] == domvalue){ this.selectlistvalue.splice(i,1) } } for(let i = 0;i<this.selectlistlabel.length;i++){ if(this.selectlistlabel[i] == domlabel){ this.selectlistlabel.splice(i,1) } } }else{ this.selectlistvalue.push(domvalue) this.selectlistlabel.push(domlabel) } }, } } </script>
style部分code
<style scoped> .active{ background-color: #0ccfbf; color: white; } </style>
注:詳細說明標註代碼上了,
須要注意的坑:對象
1.activeclass須要在computed裏面把他return出來,不然加載不到樣式。 2.對數組的操做方法,簡單點使用vue支持的變異方法(不然vue沒法檢測到數組變化,也就沒法動態綁定) 官網截了一小段圖