Kendo Grid控件中将枚举值转为枚举名显示

我们在开发过程中经常会遇到需要将枚举值转换成名称进行显示的情况。如下我们有这样一个数据源对象:

var users = [
        {id: 1, name: "similar1", status: 1},
        {id: 2, name: "similar2", status: 2}
    ];

其中字段 status 代表的是用户的状态, 1 代表 “可用”, 2 代表 “禁用”。我们使用 kendo grid 常规配置如下:

columns: [
        { field: "id", title: "编号" },
        { field: "name", title: "用户名" },
        { field: "status", title: "状态" }
    ],

对应的效果如下图所示:

由上图可见,我们的状态那一列直接就是显示的数字 1,2 ,这并不是我们想要的结果。我们需要的是将1,2分别转换成文字:可用,禁用。起初我想到的是通过 template 进行条件判断,当 status 为1时,显示 可用, 为2时, 显示 禁用。 代码如下:

columns: [
        { field: "id", title: "编号" },
        { field: "name", title: "用户名" },
        { field: "status", title: "状态", template: "#= (status == 1) ? '可用' : '禁用' #" }
    ]

// 或者

columns: [
        { field: "id", title: "编号" },
        { field: "name", title: "用户名" },
        { field: "status", title: "状态", template: "#if (status == 1) {# 可用 #}else{# 禁用 #}#" }
    ]

之后觉得这种方法太烂了,自己似乎接受不了。这种模板判断的方式维护性太低了,哪天如果加了几个状态,那就得写一堆的if。因此又去查找官方api文档,想寻找更好的解决方案,于是就有以下的收获,代码如下:

//1. 首先我们定义一个类似枚举功能的对象
var statusEnum = [
    {text: "可用", value: 1},
    {text: "禁用", value: 2}
    ]

//2. 之后对kendo grid中的配置做如下调整
columns: [
        { field: "id", title: "编号" },
        { field: "name", title: "用户名" },
        { field: "status", title: "状态", values: statusEnum }
    ]

 做完上面2步就ok了,这种方式是不是更容易被接受呢? 维护起来比之前简单了,看着也明了.....

原文地址:https://www.cnblogs.com/similar/p/5845531.html