前端枚举enum的应用(Element)封装

什么是枚举Enum

枚举 Enum是在众多语言中都有的一种数据类型,JavaScript中还没有(TypeScript有)。用来表示一些特定类别的常量数据,如性别、学历、方向、账户状态等,项目开发中是很常用的。
Text文字

(界面显示)
key编码

(编码、存储使用) 数字
value

值(存储使用) 男 male/man/nan 1 女 female/woman/nv 2 其他 other 3

如上表中的性别枚举结构,前端页面上显示文字 男、女,代码中一般使用编码 key,后端数据库存储可能会用编码key,也可能用数字 value值。用数字存储,占用空间会更小,还能用位运算存储多个值(算是稍微高级一点的玩法了)。

前端应用场景

表格数据绑定时,需要显示性别的文字信息,而后端返回的JSON数据中可能是 key/value值。

前端枚举enum的应用(Element)封装

Element 的 table组件 支持绑定一个格式化函数 formatter来转换数据,函数定义: Function(row, column, cellValue, index)
表单中提供用户的性别选项,如下拉框、单选按钮组等。

前端枚举enum的应用(Element)封装

Element 的下拉框 <el-select></el-select>通过 v-for 来绑定生成 <el-option></el-option>选项:


封装Enum数据结构

枚举数据的使用、绑定是比较常见的,针对Element UI组件进行简单封装一下,让枚举数据的使用、绑定更轻松。

  • 新建一个管理枚举数据的JS文件: enums.js
  • 定义一个枚举工厂构造函数 EnumFactory,用来封装枚举结构的基础方法,详见注释。
  • 工厂方法中通过Object.defineProperty(obj, prop, descriptor) 添加属性/方法,该方法添加的默认是不能被枚举、修改的。
  • 申明项目中公共枚举数据,并导出。
  • 枚举元数据结构:
  • 支持 {key , text}结构: { male: '&#x7537;', female: '&#x5973;', other: '&#x5176;&#x4ED6;' }
  • 也支持 {key :{text, value }}结构: { male: { text: '&#x7537;', value: 1 }, female: { text: '&#x5973;', value: 2 } }
//枚举构造器,提供的属性:
// keys:枚举的key集合[key]
// texts:枚举的文本text集合[text]
// values:枚举的数值value集合[value]
// entries:枚举的key、text、value集合[{key,text,value}]
// tableFormater:element中表格绑定枚举数据文本的formatter函数
function EnumFactory(enumObj) {
    //复制(继承)enumObj
    Object.assign(this, enumObj);

    // keys:枚举的key集合[key]
    Object.defineProperty(this, 'keys', {
        value: Object.keys(enumObj)
    });
    //处理texts、values、entries
    let values = [], texts = [], entries = [];
    const vobjs = Object.values(enumObj);
    if (typeof vobjs[0] === 'string') {
        texts = vobjs;
        vobjs.forEach((item, index) => {
            entries.push({ key: this.keys[index], text: texts[index] });
        })
    }
    else {
        vobjs.forEach((item, index) => {
            texts.push(item.text);
            values.push(item.value);
            entries.push({ key: this.keys[index], text: item.text, value: item.value });
        })
    }

    // texts:枚举的文本text集合[text]
    Object.defineProperty(this, 'texts', { value: texts });

    // values:枚举的数值value集合[value]
    Object.defineProperty(this, 'values', { value: values });

    // entries:枚举的key、text、value集合[{key,text,value}]
    Object.defineProperty(this, 'entries', { value: entries });

    // tableFormater:element中表格绑定枚举数据文本的formatter函数
    Object.defineProperty(this, 'tableFormater', {
        value: function (r, c, value) {
            return entries.filter(v => v.key === value || v.value === value)[0]?.text || 'notfound';
        }
    });

    //枚举定义的数据都是常量,不可修改,冻结一下
    Object.freeze(this);
}

//********************** 定义项目公共枚举 ********************** */

//性别枚举:key、text模式
// const enumSex = new EnumFactory({ male: '男', female: '女', other: '其他' });
//性别枚举:key、text、value模式
const enumSex = new EnumFactory({ male: { text: '男', value: 1 }, female: { text: '女', value: 2 } });
//水平对齐
const enumAlign = new EnumFactory({ left: '左对齐', center: '居中', right: '右对齐' });
//用户状态
const enumUserStatus = new EnumFactory({ default: '正常', delete: '删除', lock: '锁定' });

//**********************  export  ********************** */
export { enumSex, enumAlign, enumUserStatus }

//test
console.log(enumSex.keys);
console.log(enumSex.texts);
console.log(enumSex.values);
console.log(JSON.stringify(enumSex.entries));

// ['male', 'female']
// ['男', '女']
// [1, 2]
// [{"key":"male","text":"男","value":1},{"key":"female","text":"女","value":2}]

Element中使用

表格绑定 formatter


            修改
            查看
            删除

表单选型组件绑定选项:


        {{item.text}}

前端枚举enum的应用(Element)封装

©️ 版权申明:版权所有@安木夕(kanding),本文内容仅供学习,欢迎指正、交流,转载请注明出处!
原文编辑地址: https://www.yuque.com/kanding

Original: https://www.cnblogs.com/anding/p/16794699.html
Author: 安木夕
Title: 前端枚举enum的应用(Element)封装



相关阅读

Title: 【flask入门系列】异常处理

📋 个人简介

  • 💖 作者简介:大家好,我是阿牛,全栈领域新星创作者。😜
  • 📝 博主的个人网站:阿牛的博客小屋🔥
  • 🎉 支持我:点赞👍+收藏⭐️+留言📝
  • 📣 系列专栏:flask框架快速入门🍁
  • 💬座右铭:做光,因为有人怕黑!🔥
    [En]

    💬 motto: be the light, because there are people who are afraid of the dark! 🔥*

    前端枚举enum的应用(Element)封装

目录

*
📋 个人简介
* 前言
*
HTTP异常主动抛出
捕获错误
* 结语

; 前言

今天简单介绍一哈flask中对于异常处理的办法,算是属于表较冷门的知识点了,因为我们用python的知识来实现这些需求处理,但我们还是要学习一下,因为他可以帮我们集中处理异常,而不用在每个视图中进行异常处理。

HTTP异常主动抛出

  • abort方法
    抛出一个给定状态代码的HTTPException或者指定响应,例如想要用一个页面未找到异常来终止请求,你可以调用abort(404)
  • 参数
    code-HTTP的错误状态码。只能抛出http协议的错误代码。

from flask import Flask,request,abort
app = Flask(__name__)

@app.route('/articles')
def get_articles():
    channel_id = request.args.get('channel_id')
    if channel_id is None:
        abort(400)
    return 'you want get articles of channel {}'.format(channel_id)

if __name__ == '__main__':
    app.run(port=8000)

前端枚举enum的应用(Element)封装

捕获错误

  • errorhandler装饰器
    注册一个错误处理程序,当程序引发指定的错误状态代码时,它会调用由修饰符修饰的方法。
    [En]

    Register an error handler, and when the program throws a specified error status code, it calls the method decorated by the decorator.

  • 参数
    code_or_exception – HTTP的错误状态码或指定异常。
  • 例如统一处理状态码为500的错误给用户有好的提示。
@app.errorhandler(500)def internal_server_err(e):    return "服务器搬家了"
  • 捕获指定异常
@app.errorhandler(ZeroDivisionError)def zero_division_err(e):    return "除数不能为零"

例:


from flask import Flask
app = Flask(__name__)

@app.errorhandler(ZeroDivisionError)
def zero_division_err(e):

    print(e)
    return "除数不能为零"

@app.route("/")
def index():
    s = 1/0
    return s

if __name__ == '__main__':
    app.run(port=8000)

前端枚举enum的应用(Element)封装
前端枚举enum的应用(Element)封装
从图中可以看到,当遇到异常时,当前视图的执行将立即停止,并执行对应的异常处理视图。
[En]

As can be seen from the diagram, the execution of the current view will be stopped immediately when an exception is encountered, and the corresponding exception handling view will be executed.

结语

如果你觉得博主的文章写得不错,你可以关注当前的专栏,博主将完成这一系列!你也可以订阅博主的其他好专栏。

[En]

If you think the blogger’s writing is good, you can follow the current column, the blogger will finish this series! You are also welcome to subscribe to other good columns of the blogger.

🏰系列专栏
👉软磨 css
👉硬泡 javascript
👉前端实用小demo

Original: https://blog.csdn.net/qq_57421630/article/details/125812258
Author: 馆主阿牛
Title: 【flask入门系列】异常处理

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/363453/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总