1.定义工具类
// 格式化时间
function FormatDate (time: string) {
if (Tool.isNotEmpty(time)) {
const date = new Date(time)
// 注意js里面的getMonth是从0开始的
let FormattedDateTime = null
const year = date.getFullYear()
const month = (date.getMonth() + 1)
const day = date.getDate()
let h: string | number = date.getHours()
let m: string | number = date.getMinutes()
let s: string | number = date.getSeconds()
h = h < 10 ? '0' + h : h
m = m < 10 ? '0' + m : m
s = s < 10 ? '0' + s : s
FormattedDateTime = year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
return FormattedDateTime
}
return null
}
2.在main.ts/main.js 中进行引入,并挂载全局方法
- 在main.ts入口文件进行引入
import { FormatDate } from '@/util/utils'
2. 挂载到全局方法
vue3 使用 app.config.globalProperties 进行全局方法的定义,全局方法定义后,就无需每个页面使用时,进行单独引用了。
const app = createApp(App)
app.config.globalProperties.$formatTime = FormatDate
3.页面使用
3.1 在template中使用时,可以直接使用
使用在main.ts定义的名称($formatTime)进行方法的引用
3.2 在script中使用,需要获取到 getCurrentInstance实例再进行使用
// 在main.js中,进行挂载
app.config.globalProperties.$axios = axios;
// 在页面 script使用
<script setup>
import { ref, getCurrentInstance } from 'vue'
// proxy相当于 vue2的this,从getCurrentInstance 实例中获取,proxy对象
const { proxy } = getCurrentInstance()
const getData = () => {
proxy.$axios.get("https://www.baidu.com")
}
</script>