close
今天要來介紹使用Vue實作出表格裡的欄位選項被選擇時會改變顏色
呈現出來的畫面就會像這樣
HTML
<div class="row" id="app">
<div class="col-12" >
<table class="table">
<thead>
<tr>
<th hidden></th>
<th>heard1</th>
<th>heard2</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in itemList"
@click="selItem(item)"
:class="{ clicked: opened.includes(item.id) }">
<td hidden>
<div>
<input type="checkbox"
:id="'item'+index"
:value="item"
v-model="checkedItems">
</div>
</td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
在tbody、tr裡設定click事件(selItem)
,以及綁定class(clicked)
然後再第一個td欄位裡放input checkbox並設定成hidden
Vue
new Vue({
el: "#app",
data: {
itemList:[
{ id: 1, name: 'item1', value: 1 },
{ id: 2, name: 'item2', value: 2 }
],
opened:[],
checkedItems:[]
},
methods:{
selItem(item){
const index = this.opened.indexOf(item.id);
if(index > -1){
this.opened.splice(index,1);
this.checkedItems.splice(index,1);
} else {
this.opened.push(item.id);
this.checkedItems.push(item);
}
}
}
});
在我們設定的click事件(selItem)
將opened用indexOf
找尋有無id存在
如果沒找到id便用push
加到opened陣列裡
反之indexOf
找不到會回傳-1那就用splice
將opened陣列裡的id移除
CSS
.clicked {
background-color: #26C6DA;
}
在Html畫面上我們有設定class(clicked)
這邊我們就設定背景顏色(background-color
)
補充
文章標籤
全站熱搜
留言列表