L
L
lolrofl012019-02-21 23:21:36
JavaScript
lolrofl01, 2019-02-21 23:21:36

How to work with moment.js inside vue.js?

Hey!
I am making a very simple script with dates, I wanted to do it as soon as possible without using webpack, I just added vue (because I need reactivity) and added moment. Moment works fine without vue. But inside vue itself, it says that the function is undefined. Okay, I understand what vue is looking for in its local area, and I found such a solution. In methods add:

moment: function () {
            return moment();
        }

And still writes that the function is undefined.
Here is the code:
var moment = moment();

var app = new Vue({
    el: '#wrapper',
    data: { },
    methods: {
        makeCalculate: function () {
             var today = moment.format('DD.MM.YYYY');  //отлично работает
       },
       moment: function () {
            return moment();
        }
}
});

So, it was necessary to pass the argument to the moment () function. In the code where the comment "works great" moment() works through a variable, so the argument cannot be passed in any way ((. But moment() or this.moment() (with reference to the vue method) return "TypeError: moment is not a function". How to be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavlo Ponomarenko, 2019-02-21
@lolrofl01

var moment = moment();
The problem is this. At the moment when you write var moment- the global variable in this context is forgotten and the local one appears. Accordingly, when you do = moment()- it does not refer to the global variable that the library created, but to the local one that you just created.
Just remove this line and everything should work:
var moment = moment();

L
Lumore, 2019-02-22
@Lumore

main.js

import Vue from 'vue';
import moment from 'moment';
Vue.prototype.$moment = moment;

const app = new Vue({
    el: '#wrapper'
});

component:
methods: {
        makeCalculate () {
             return this.$moment().format('DD.MM.YYYY');
       }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question