Moment.js with Vuejs
我尝试使用
1 | {{ moment().format('MMMM Do YYYY, h:mm:ss a') }} |
但是,它不会出现。 只是一片空白。 我该如何尝试在瞬间发挥作用?
对于您的代码,
因此,您应该使用如下方法:
1 2 3 4 5 | methods: { moment: function () { return moment(); } }, |
如果要将日期传递给
1 2 3 4 5 6 7 | filters: { moment: function (date) { return moment(date).format('MMMM Do YYYY, h:mm:ss a'); } } <span>{{ date | moment }}</span> |
[演示]
如果您的项目是单页应用程序(例如,由
我发现这种方式最直观,最简单:
在main.js中
1 2 3 | import moment from 'moment' Vue.prototype.moment = moment |
然后在您的模板中,只需使用
1 | <span>{{moment(date).format('YYYY-MM-DD')}}</span> |
在
1 2 3 4 | "dependencies": { "moment":"^2.15.2", ... } |
在您想使用力矩的组件中,将其导入:
1 2 | import moment from 'moment' ... |
并在同一组件中添加一个计算属性:
1 2 3 4 5 | computed: { timestamp: function () { return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm') } } |
然后在此组件的模板中:
1 2 3 | <p> {{ timestamp }} </p> |
我在单个文件组件中将其与Vue 2.0一起使用。
安装了vue的文件夹中的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <template> {{ getHumanDate(meta.value.date) }} </template> import moment from 'moment'; export default { methods: { getHumanDate : function (date) { return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY'); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // plugins/moment.js import moment from 'moment'; moment.locale('ru'); export default function install (Vue) { Object.defineProperties(Vue.prototype, { $moment: { get () { return moment; } } }) } // main.js import moment from './plugins/moment.js'; Vue.use(moment); // use this.$moment in your components |
这是一个使用名为
除了将Moment实例绑定到Vue的根范围外,该库还包括
此示例包括本地化,并且使用的是ES6模块导入(一种官方标准),而不是NodeJS的CommonJS模块系统所要求的。
1 2 3 4 5 6 7 8 9 10 11 12 | import Vue from 'vue'; import moment from 'moment'; import VueMoment from 'vue-moment'; // Load Locales ('en' comes loaded by default) require('moment/locale/es'); // Choose Locale moment.locale('es'); Vue.use(VueMoment, { moment }); |
现在,您可以直接在Vue模板中使用Moment实例,而无需任何其他标记:
1 | <small>Copyright {{ $moment().year() }}</small> |
或过滤器:
1 2 3 4 | <span>{{ 3600000 | duration('humanize') }}</span> <!--"an hour" --> <span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span> <!--"3 years" --> |
vue-moment
vue项目的非常不错的插件,并且与组件和现有代码非常流畅地工作。
享受瞬间... ??
1 2 3 4 5 6 | // in your main.js Vue.use(require('vue-moment')); // and use in component {{'2019-10-03 14:02:22' | moment("calendar")}} // or like this {{created_at | moment("calendar")}} |
我只需要导入moment模块,然后使用计算函数来处理我的moment()逻辑并返回模板中引用的值即可。
虽然我没有使用它,因此不能说它的有效性,但我确实找到了https://github.com/brockpetrie/vue-moment作为替代考虑