因為是學習vue我也是剛入門,只是簡單的記錄一下學習過程中用到的小組件和小問題,就不做其他的描述了
需求:標簽的多選/反選
我使用的是 Element組件,具體安裝就不說了自行百度
使用 el-row 嵌套 el-button 的方法:
<el-row class="wp-list">
<el-button
class="margin-top-10"
v-for="item in interestList"
:key="item.interestName"
:class="{ active: item.isSelected }"
@click="selected(item)"
>{{ item.interestName }}</el-button
>
</el-row>
在data中初始化數據
data() {
return {
interestList: [],//用來初始化數據 例 PS:[{id:1,interestName:"標簽1",isSelected:false}] 這個可以根據自己的需求自行定義 我在數據中默認添加了一個isSelected字段用來區別標簽是否選中 true:選中狀態 ,false:未選中狀態
interestSelected: [] //保存選擇標簽 例 PS:[1,2,4]//存放內容為標簽的id 此值唯一(可自行根據自己的需求定義)
}
}
定義標簽style
//定義選中狀態的背景和邊框顏色(可根據需求自行定義)
<style scoped>
.margin-top-10 {
margin-top: 10px;
}
.active {
background: #fd7522;
border: 1px solid #fd7522;
color: #fff;
}
</style>
定義方法 用以響應修改點擊時標簽的狀態
methods: {
selected(item) {
//點擊時狀態置反 true -> false / false -> true
item.isSelected = !item.isSelected
//判斷當修改過的狀態為true時將此標簽id存放進數組中
if (item.isSelected) {
this.interestSelected.push(item.id)
} else {
//否則將此id從數組中移除
this.interestSelected.splice(this.interestSelected.indexOf(item.id), 1)
}
}
}
拿到此選中標簽集合可進行后續操作,比如說上傳到服務器更新數據庫等等
下面是效果圖:
效果預覽
2021.07.07 17:21:06 周三 多云