Vue.js and vue-moment: “Failed to resolve filter:

2019-04-14 17:37发布

Trying to use vue-moment. The simplest possible example from the documentation doesn't work: https://jsfiddle.net/rjcpz9wt/

<span>{{ new Date() | moment "dddd, MMMM Do YYYY" }}</span>

Gives:

[Vue warn]: Failed to resolve filter: moment

What is going on?

3条回答
小情绪 Triste *
2楼-- · 2019-04-14 18:17

/////EDIT/////

apparently you don't need to put moment inside a Vue.filter(....) at all.

after you entered Vue.use(VueMoment) in main.js, simply put a filter as shown in their documentation anywhere in your app and it just works

//////////////

I encountered the same problem, solved it by not using vue filters

this is my workaround, my main.js looks like this:

import Vue from 'vue'
import VueMoment from 'vue-moment';

Vue.use(VueMoment)

and in the component wherever i need to use moment it looks like this:

//IN METHODS:
methods: {
    tellTime(time) {
      console.log(this.$moment(time).format(' mm:ss'))
    }
}
<!-- OR IN TEMPLATE -->
      {{$moment(timestamp).fromNow()}}

Hope someone else would find it useful :)

查看更多
混吃等死
3楼-- · 2019-04-14 18:22

I wouldn't suggest doing it the way you are, you should create the date variable in the javascript code and just access the variable in your Vue. Here is a fiddle showing what I mean

https://jsfiddle.net/rdffywc7/

var app = new Vue({
  el: document.body,
  data: {
    date: moment().format("ffffdd, MMMM Do YYYY")
  }
})

and then in the doc body

<span>{{ date }}</span>
查看更多
倾城 Initia
4楼-- · 2019-04-14 18:31

vue-moment is broken.

You can't use it by just adding it as a <script> tag. Currently it only works if you use compile it with webpack or browserify, see this issue for updates.

It used to work well on the original version: https://github.com/brockpetrie/vue-moment/tree/fd6fcb901415c1df4c5abb81870d49b346d3732f

See the original version working here: https://jsfiddle.net/gerardog/vaw33sn2/

Also, on Fiddle dont link to files in https://raw.github.com/ , use this nice workaround

查看更多
登录 后发表回答