创建一个全局方法
app.config.globalProperties.$dateFormat = (date: string) => {
if (!date) return ''
return new Date(date).toLocaleString('zh-CN')
}
创建一个文件,用于调用公共方法
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export const useCurrentInstance = () => {
const { appContext } = getCurrentInstance() as ComponentInternalInstance
const proxy = appContext.config.globalProperties
return {
proxy
}
}
使用
<template>
<div>
{{ proxy?.$dateFormat(date) }}
</div>
</template>
<script setup lang="ts">
import { useCurrentInstance } from '@/utils/useCurrentInstance'
const { proxy } = useCurrentInstance()
</script>