一、在项目package-lock.json配置好moment-timezone
{ "name": "dashboard", "version": "0.1.0", "lockfileVersion": 1, "requires": true, "dependencies": { ....... "moment-timezone": { "version": "0.5.28", "resolved": "http://r.cnpmjs.org/moment-timezone/download/moment-timezone-0.5.28.tgz", "integrity": "sha1-8JPXidCR7XsFXYKqgagkZ/cuQzg=", "requires": { "moment": ">= 2.9.0" } }, ........ } }
二、在项目package.json
{ "name": "dashboard", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^3.6.4", "element-ui": "^2.13.0", "js-cookie": "^2.2.1", "jwt-decode": "^2.2.0", "moment": "^2.24.0", "moment-timezone": "^0.5.28", "vue": "^2.6.10", "vue-headful": "^2.1.0", "vue-i18n": "^8.15.3", "vue-moment": "^4.1.0", "vue-router": "^3.1.5", "vuex": "^3.1.2" }, ...... }
三、在项目的主js里面导入和导出
import Vue from "vue"; import VueMoment from "vue-moment"; import moment from "moment-timezone"; import "moment/locale/zh-cn"; import ElementUI from "element-ui"; import Headful from "vue-headful"; Vue.use(VueMoment, { moment }); Vue.use(ElementUI); Vue.component("head-ful", Headful); export const DATE_FORMAT = "yyyy-MM-dd"; export const ALL = "all"; export const TIMESTAMP_FORMAT = "YYYY-MM-DD HH:mm:ss";//这是具体到秒 export const TIMESTAMP_DATE_FORMAT = "YYYY-MM-DD";//这是具体到天
四、在页面中应用
<template> ...... <el-table-column label="更新于" width="110"> <template slot-scope="scope">{{ scope.row.fytjdwgl.updatedAt|moment(TIMESTAMP_FORMAT) }}</template> </el-table-column> ..... </template> <script> import { TIMESTAMP_FORMAT } from "@/components"; export default { data() { return { TIMESTAMP_FORMAT }; }, created(){}, methods:{} }; </script>
对于可为空的日期格式化需要先进行v-if判空
<template slot-scope="scope"> <span v-if="scope.row.yshtgl.djrq"> {{ scope.row.yshtgl.djrq| moment(TIMESTAMP_DATE_FORMAT) }} </span> </template>
五、想了解更多
Vue中使用 moment 格式化时间 请去这里看详细moment