1、定义全局方法
//main.ts
//定义全局方法
app.config.globalProperties.$filters = {
//app.config.globalProperties.+你想添加的属性 $filters 加美元符号主要是为了区分和组件内部的属性
//全局属性,在里面加东西任何地方都能用
formatTime() {
//格式化时间
return '2021-12-14'
}
}
2、在shims-vue.d.ts声明在main.ts中定义的全局方法
/* eslint-disable */
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
//在ComponentCustomProperties里面声明在main.ts定义的全局方法和属性
interface ComponentCustomProperties {
//声明全局方法
$filters: {
formatTime: () => string;
}
}
}
3、在任意组件中使用
// 部分代码
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const time = instance?.appContext.config.globalProperties.$filters.formatTime()
console.log(time)
4、结果展示
如有其他想法可以分享一下,谢谢