我們經(jīng)常會遇到一種情況,打個比方,我們需要顯示商品的狀態(tài)。
狀態(tài)state為代付款,代發(fā)貨, 待收貨,待評價,無狀態(tài)五種,而后端返回給我們的是1,2,3,4,5這樣的數(shù)值。
一開始我的處理方式是拿到數(shù)據(jù)之后遍歷,挨個修改每個state的值,這樣的話在修改提交的時候,又需要經(jīng)歷一遍遍歷將state變?yōu)楹蠖诵枰臄?shù)值,很麻煩,代碼量也大大增加。
后來了解到利用filters和switch來處理,真的超級方便快捷,學習起來~~
補充:動態(tài)類名也可以是使用過濾器哦
//template
<table border="1">
<tr v-for="(item,index) in array" :key="index">
<th>{{item.name}}</th>
<th :class="item.status | filter2 | filter3">{{item.status | filter2}}</th>
</tr>
</table>
//filters 數(shù)值轉(zhuǎn)文字
filter2: function (value) {
switch(value){
case 1:return `代付款`;
case 2:return `代發(fā)貨`;
case 3:return `待收貨`;
case 4:return `待評價`;
default:return `無狀態(tài)`;
}
},
//文字轉(zhuǎn)類名
filter3: function (value) {
switch (value) {
case `代付款`:
return 'red';
case `代發(fā)貨`:
return 'yellow';
case `待收貨`:
return 'blue';
case `待評價`:
return 'green';
default:
return 'white';
}
},
//data
array: [
{ status: 1, name: "衣服" },
{ status: 2, name: "褲子" },
{ status: 3, name: "內(nèi)褲" },
{ status: 4, name: "秋衣" },
{ status: 5, name: "襪子" },
],