• 1. vue-sy-admin: 基于vue3+TypeScript的全局过滤器(filters) 封装及示例


    vue3中使用全局filters已经不是必须,有很多种替代方案(直接定义函数即可)。如果项目中使用了unplugin-auto-import插件完全可以将filters导出函数使其在全局自动引入/声明。当然在这里就不说插件的使用了。下面就详细说说如何实现

    题外话: 强烈推荐使用 vueuse,该库由vue核心成员开发,封装了各种常用hooks,能够省很多不必要的开发时间,且其中的封装hooks思想也很值得学习参考

    最终效果如下图所示

    Snipaste_2023-10-13_11-55-00.png

    1. filters工具函数建立及类型参数声明

    src/filters目录下新建 index.tstypes.ts 分别用于全局filters的注册及全局参数声明

    // index.ts
    
    // useDateFormat 为 vueuse 提供的时间格式化hooks,内部实现基于dayjs
    import { useDateFormat } from '@vueuse/core';
    
    import type { App } from 'vue';
    
    export default function filters(app: App) {
      app.config.globalProperties.$filters = {
        dateFormat: (date, format = 'YYYY-MM-DD hh:mm:ss', options = {}) => {
          return useDateFormat(date, format, options).value;
        },
      };
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    // types.ts
    import type { MaybeRefOrGetter,  DateLike, UseDateFormatOptions } from '@vueuse/core';
    
    export interface Filter {
      dateFormat: (
        date: MaybeRefOrGetter<DateLike>,
        format?: MaybeRefOrGetter<string>,
        options?: UseDateFormatOptions
      ) => string;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注:types.ts导出接口声明主要用于在vue组件的ComponentCustomProperties中作声明使用

    2. 注册全局filters

    在入口文件 main.ts中引入并注册即可

    // main.ts
    import { createApp } from 'vue';
    import filters from './filters';
    
    const app = createApp(App);
    app.use(filters);
    app.mount('#app');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    注册完之后就可以在页面中使用了,不过因为目前还没有添加类型提示,页面会爆红。

    3. 为.vue文件添加filters类型声明

    // global-properties.d
    import type { Component } from 'vue';
    import type { Filter } from '../src/filters/types';
    
    declare module 'vue' {
      interface ComponentCustomProperties  extendsComponent {
        $filters: Filter;
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    注:别忘了将该文件加入tsconfig.json的include配置项中,否则在.vue文件的template中使用将不会出现类型提示。

    在线代码可查看:vue-sy-admin
    简易模板可查看:vue-vite-template

  • 相关阅读:
    java酒店预订网站设计与实现
    学习(踩坑)日记:paramiko,yield,pywin32,ctypes,airflow,clickhouse_driver
    不止于观测|阿里云可观测套件正式发布
    如何查看go依赖包的license (glice)
    14:00面试,14:06就出来了,问的问题有点变态。。。。。。
    React和Redux中的不变性
    Spring Bean 生命周期
    计算机毕业设计 | springboot+vue会议室管理系统(附源码)
    Qt 实现文字输入框,带字数限制
    Mac连接linux的办法(自带终端和iterm2)
  • 原文地址:https://blog.csdn.net/weixin_42386379/article/details/133811524