- The server usually returns a timestamp, which is usually 10 digits and the representative unit is seconds. Or 13 bits, the representative unit is milliseconds
Realization effect:
1. app.vue
<template>
<div class="app">
<h2 v-ftime>{
{ timetamp }}</h2>
<h2 v-ftime="'YYYY-MM-DD'">{
{ 1230098765678 }}</h2>
<h2 v-ftime>{
{ timetamp }}</h2>
</div>
</template>
<script setup>
const timetamp = 1231231230
</script>
<style scoped></style>
2. Custom command v-ftime
- Create new directives/ ftime.js
- Download npm i day.js
import dayjs from 'dayjs'
export default function directiveFtime(app) {
app.directive('ftime', {
mounted(el, bindings) {
// 1.获取时间,并转化成毫秒
let timestamp = el.textContent
console.log(timestamp) // 1231231230
if (timestamp.length === 10) {
// 这里有 * 可以隐式转换成数字型
timestamp = timestamp * 1000
}
// 因为如果timestamp是 13位数的话,是字符串类型,这里需要转成数字型
timestamp = Number(timestamp)
// console.log(timestamp) // 1231231230000
// 2.获取传入的参数
let value = bindings.value
if (!value) {
value = 'YYYY-MM-DD HH:mm:ss'
}
// 2.对时间进行格式化
const formatTime = dayjs(timestamp).format(value)
el.textContent = formatTime
}
})
}
3.directives/index.js
import directiveFtime from './ftime'
export default function useDirectives(app) {
directiveFtime(app)
}
4.main.js
import { createApp } from 'vue'
import App from './01_自定义指令/App.vue'
import useDirectives from './01_自定义指令/directives/index'
const app = createApp(App)
// 自定义指令
useDirectives(app)
app.mount('#app')