引入 moment
安装
yarn:
1
yarn add moment
npm:
1
npm i moment
配置
在plugins目录下,新建文件:
moment.js
,放入以下内容:1
2
3
4
5
6
7import Vue from 'vue'
import moment from 'moment'
Vue.filter('moment', function(value, pattern = 'YYYY-MM-DD HH:mm:ss') {
if (!value) { return null }
return moment(value).format(pattern)
})这里设置了默认的时间样式是YYYY-MM-DD HH:mm:ss。
最后,在
nuxt.config.js
文件的plugins中添加:1
2
3
4
5plugins: [
'xxxx',
// 引入我们刚刚新增的文件moment.js
'~/plugins/moment'
]
OK ,重启后就可以开始用了。
全局设置多种格式
比如需要配置两种格式,日期型和时间型。
修改plugins/moment.js
:
1 | import Vue from 'vue' |
这里,设置默认为日期格式。
页面使用
比如需要显示商品创建时间:
1 | {{ product.created_at | moment('datetime') }} |
因为设置了参数format默认是date, 当moment内不传参数时,则采用日期样式。