在實(shí)際項(xiàng)目的開發(fā)中,常常會(huì)遇到一種情況,比如:表格中存在支付類型這個(gè)字段般码,后臺(tái)返回的為數(shù)字1,2,3,4等锅减,然后我們前端就需要就后臺(tái)返回的數(shù)字類型轉(zhuǎn)換為對(duì)應(yīng)的支付類型渲染到對(duì)應(yīng)的表格中去。
這種有很多方法去處理钝吮,比如之前我經(jīng)常考慮用render函數(shù)去處理它,但是實(shí)際上漆羔,使用過濾器
的話,會(huì)更方便狱掂。
1演痒、現(xiàn)在vue實(shí)例外部定義一個(gè)對(duì)應(yīng)的列表項(xiàng)
const payTypeOptions = [
{ type: "1", name: "微信支付" },
{ type: "2", name: "支付寶支付" },
{ type: "3", name: "銀行卡支付" },
{ type: "4", name: "現(xiàn)金支付" },
];
這個(gè)必須要在Vue實(shí)例外部去寫,不能寫在data選項(xiàng)中趋惨,因?yàn)樵谶^濾器當(dāng)中鸟顺,不能引用當(dāng)前實(shí)例this, 所以需要在實(shí)例外部去定義!
2、開始寫過濾器代碼
filters: {
payTypeFilter(type) {
const isPayType = payTypeOptions.find((obj) => {
return obj.type === type;
});
return isPayType ? isPayType.name : "";
},
},
如果在列表項(xiàng)中找到該項(xiàng)器虾,那么就返回它的name讯嫂,也就是支付類型。
3兆沙、element-ui表格的處理
<el-table-column prop="paytype" label="支付方式" width="180">
<template slot-scope="scope">
<el-tag
:type="
scope.row.paytype == '1'
? 'success'
: scope.row.paytype == '2'
? 'info'
: scope.row.paytype == '3'
? 'warning'
: ''
"
>{{ scope.row.paytype | payTypeFilter }}</el-tag
>
</template>
</el-table-column>