使用ts给vue3的globalProperties挂载全局方法+智能提示
使用ts给vue3的globalProperties挂载全局方法+智能提示
【vue3.2】 版本参考如下:
https://blog.feiyuit.cn/archives/187.html
以下为 【vue3.0】 版本:
效果
VSCode插件:Volar
方法定义
// date.ts
import moment from 'moment'
/**
* 日期时间格式化
* @param time 需要格式化的日期时间
* @param format 指定格式,默认YYYY-MM-DD HH:mm:ss
* @returns 格式化后的字符串
*/
export function formatDate(time: string, format = 'YYYY-MM-DD HH:mm:ss') {
if (time == null) return ''
const date = new Date(time)
return moment(date).format(format)
}
挂载方法
// main.ts
const app = createApp(application)
app.config.globalProperties.$formatDate = formatDate
类型定义
// components.d.ts
import { formatDate } from '@/common/date'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
// Example:
// $http: typeof axios
// $validate: (data: object, rule: object) => boolean
$formatDate: typeof formatDate
}
}
模板使用
// xxxxx.vue
<div>
<div class="field">
<label>Time</label>:
<span>{{ $formatDate(data.materialApplyForm.sapApplyAt) }}</span>
</div>
</div>
参考
https://v3.vuejs.org/guide/typescript-support.html#augmenting-types-for-globalproperties
https://marketplace.visualstudio.com/items?itemName=johnsoncodehk.volar