vue3.0 + ts 全局引用 dayjs

6,148 阅读1分钟

地址

dayjs文档: dayjs.gitee.io/docs/zh-CN/…

github: github.com/iamkun/dayj…

安装

npm install dayjs

在 TypeScript 项目中导入并使用

import * as dayjs from 'dayjs';
dayjs().format();

导入本地化语言和插件

import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // 导入插件 
import 'dayjs/locale/zh-cn' // 导入本地化语言 

dayjs.extend(isLeapYear) // 使用插件 
dayjs.locale('zh-cn') // 使用本地化语言

vue3.0 全局安装

  1. 创建文件/dayjs/index.ts,写入:
import * as dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { App } from "vue";

dayjs.locale("zh-cn");

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    readonly $dayjs: any;
  }
}

export default {
  install: (app: App<Element>): void => {
    app.config.globalProperties.$dayjs = dayjs;
  },
};
  1. main.ts 注册
import dayjs from "./dayjs";
const app = createApp(App);
app.use(dayjs);
  1. 查看
import { getCurrentInstance } from "vue";

const proxy = getCurrentInstance()?.proxy;
const dayjs = proxy?.$dayjs;
const now = dayjs ? dayjs().format("YYYY年MM月DD日 dddd") : "";

console.log(now);