自定义指令案例:时间戳的转换
安装dayjs库,方便对时间戳做转换:
npm install dayjs
App.vue:
<template>
<div>
<h2 v-format-time>{{ timeStamp }}</h2>
</div>
</template>
<script>
export default {
setup() {
const timeStamp = 1659935604;
return {
timeStamp,
};
},
};
</script>
format-time.js:
import dayjs from 'dayjs'
export default function formatTime(app) {
app.directive('format-time',{
mounted(el,bindings) {
//拿到标签里的内容
let textContent = el.textContent
//将字符串转换成整数
let timestamp = parseInt(textContent)
// 传入的需要转换的形式,如果没有传入则使用默认形式
let formatString = bindings.value
if(!formatString) {
formatString = 'YYYY-MM-DD HH:mm:ss'
}
//将秒转成毫秒
if(textContent.length === 10) {
timestamp = timestamp * 1000
}
//传入dayjs函数的时间戳需要是毫秒单位
el.textContent = dayjs(timestamp).format(formatString)
},
})
}