关于momentjs:Moment.js与Vuejs

Moment.js with Vuejs

我尝试使用vue-for中的以下内容打印日期时间

1
{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}

但是,它不会出现。 只是一片空白。 我该如何尝试在瞬间发挥作用?


对于您的代码,vue.js试图从其作用域访问moment()方法。

因此,您应该使用如下方法:

1
2
3
4
5
methods: {
  moment: function () {
    return moment();
  }
},

如果要将日期传递给moment.js,我建议使用过滤器:

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>

[演示]


如果您的项目是单页应用程序(例如,由vue init webpack myproject创建的项目),
我发现这种方式最直观,最简单:

在main.js中

1
2
3
import moment from 'moment'

Vue.prototype.moment = moment

然后在您的模板中,只需使用

1
<span>{{moment(date).format('YYYY-MM-DD')}}</span>

"dependencies"部分的package.json中添加矩:

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的文件夹中的npm install moment

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


这是一个使用名为vue-moment的Vue的第三方包装库的示例。

除了将Moment实例绑定到Vue的根范围外,该库还包括momentduration过滤器。

此示例包括本地化,并且使用的是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作为替代考虑