openks / learn-vue

自定义组件文档
https://openks.github.io/learn-vue
0 stars 0 forks source link

20171122-垃圾代码引发思考 #65

Open openks opened 6 years ago

openks commented 6 years ago

垃圾代码印发的思考
看到项目里类似如下代码感觉肯定会有更好的写法:

<template slot-scope="scope">
    <el-tag type="primary" v-if="scope.row.status === '10'">已发单</el-tag>
    <el-tag type="success" v-if="scope.row.status === '11'">已接单</el-tag>
    <el-tag type="danger" v-if="scope.row.status === '12'">已提交</el-tag>
    <el-tag type="gray" v-if="scope.row.status === '13'">已完成</el-tag>
    <el-tag type="" v-if="scope.row.status === '14'">已撤销</el-tag>
    <el-tag type="warning" v-if="scope.row.status === '15'">已退回</el-tag>
    <el-tag type="warning" v-if="scope.row.status === '16'">已放弃</el-tag>
    <el-tag type="danger" v-if="scope.row.status === '17'">处理中</el-tag>
    <el-tag type="gray" v-if="scope.row.status === '18'">已过期</el-tag>
    <el-tag type="primary" v-if="scope.row.status === '19'">待发单</el-tag>
</template>

以上代码具体功能:
1.根据不同的状态码显示不同的文字
2.根据不同的状态码显示不同的type

仔细一想发现可以用filter来处理这种情况

let State = [
    {
        code: '10',
        type: 'success',
        text: '接受10'
    },
    {
        code: '11',
        type: 'primary',
        text: '接受11'
    },
    {
        code: '12',
        type: 'warning',
        text: '接受12'
    }
]
/**
 * 状态拦截器
 * @method   stateFilter
 * @param    {String}                value 接收的code
 * @param    {String}                key   "type"||"text"
 * @return   {String}  要显示的值
 * @datetime 2017-11-22T22:30:11+080
 */
let stateFilter = (value, key) => {
    let returnObj = ''
    let tmp = State.filter(function (item) {
            return item.code === value
    })
    if (tmp.length !== 0) {
        returnObj = tmp[0][key]
    }
    return returnObj
}

经过配置后一行代码即可解决
而且可以多处通用

<template slot-scope="scope">
  <el-tag :type="scope.row.status | stateFilter('type')">{{scope.row.status | stateFilter("text")}}</el-tag>
</template>
openks commented 6 years ago

也就是用vue全局filter 更多信息#35