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

后端 未结 4 1295
时光说笑
时光说笑 2021-02-10 09:06

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

{{ new Date() | moment \         


        
相关标签:
4条回答
  • 2021-02-10 09:25

    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

    0 讨论(0)
  • 2021-02-10 09:28

    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>
    
    0 讨论(0)
  • 2021-02-10 09:33

    /////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 :)

    0 讨论(0)
  • 2021-02-10 09:38

    My answer may be too late but still useful for others who are facing this problem right now. As @Gerardo Grignoli said, vue-moment is broken so personally I used

    import moment from "moment"
    Vue.prototype.$moment = moment; 
    // later in component 
    computed: {
        theDate(){ 
            return this.$moment('2019-10-30T11:10:21.484894Z').format('DD.MM.YYYY'); 
        }
    }
    
    0 讨论(0)
提交回复
热议问题