vue3 项目中使用 dayjs

4,261 阅读1分钟

Day.js是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。

安装 dayjs

npm i dayjs -D

main.js 全局挂载

// vue2
import Vue from 'vue'
import dayjs from 'dayjs'

Vue.prototype.$dayjs = dayjs

// vue3
import { createApp } from 'vue'
import App from './App.vue'
import dayjs from 'dayjs'

const app = createApp(App)
app.config.globalProperties.$dayjs = dayjs

页面中使用 dayjs

<template>
  <div class="wrapper">
    <!-- vue2 -->
    {{ $dayjs('20221214').format('YY-MM-DD HH:mm:ss') }}
    <!-- vue3 -->
    {{ $dayjs('20221214').format('YY-MM-DD HH:mm:ss') }}
  </div>
</template>

<script>
// vue2
export default {
  computed() {
    currentTime() {
      const date = new Date()
      return this.$dayjs(date).format('YY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<script setup>
// vue3
import { computed, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
const currentTime = computed(() => {
  const date = new Date()
  return proxy.$dayjs(date).format('YY-MM-DD HH:mm:ss')
})
</script>