marcelo2605
marcelo2605

Reputation: 2794

Using Moment.js as a plugin inside main.js

I registered Moment.js as a plugin, like this:

import Vue from 'vue'
import moment from 'moment'

moment.locale('pt_BR')

Vue.use({
  install (Vue) {
    Vue.prototype.$moment = moment
  }
})

Now, I need to use this in my main.js filters

import './plugins/moment'

Vue.filter('formatDate', value => {
  return this.$moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY')
})

Buth this return an error:

Error in render: "TypeError: Cannot read property '$moment' of undefined"

Upvotes: 0

Views: 372

Answers (2)

MJ_Wales
MJ_Wales

Reputation: 893

Vue.filter() creates a global filter before the Vue instance is created, a global filter does not have access to the Vue instance therefore you can not access this.$moment. If you need to access the vue instance, you'll need to register a local filter on components.

However, you could rectify this by directly referencing the module:

import moment from 'moment';

Vue.filter('formatDate', value => {
  moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY')
});

Upvotes: 1

Vinicius Santin
Vinicius Santin

Reputation: 620

Looks like you can not access this like in the vue components for filter methods.

By Evan You

This is intentional in 2.x. Filters should be pure functions and should not be dependent on this context. If you need this you should use a computed property or just a method e.g. $translate(foo)

I guess the best way is importing the moment on main.js like this:

import moment from 'moment'

Vue.filter('formatDate', value => {
  return moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY')
})

Upvotes: 2

Related Questions