nuxt-community / moment-module

Efficient Moment.js integration for Nuxt
MIT License
195 stars 12 forks source link

Can't use in plugin #4

Closed rktyt closed 5 years ago

rktyt commented 6 years ago

nuxt.config.js

  ...
  modules: [
    '@nuxtjs/axios',
    ['@nuxtjs/moment', ['ja']]
  ],
  plugins: [
   ...
    '~/plugins/formatter.js',
   ...
  ],
  ...

~/plugins/formatter.js

export default ({ app }, inject) => {
  inject('versionFormat', (date) => app.$moment(date).format('YYYY/MM/DD HH:mm:ss.SSS'))
}

The above code doesn't work because app.$moment is undefined. Maybe same as #3.


I want you to change it like @nuxtjs/axios module.

https://github.com/nuxt-community/moment-module/blob/master/lib/moment.plugin.js

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

<%= options.locales.map(l => `import 'moment/locale/${l}'`).join('\n') %>

-if (!Vue.prototype.hasOwnProperty('$moment')) {
-  Object.defineProperty(Vue.prototype, '$moment', {
-    get() {
-      return moment
-    }
-  })
-}
+export default (ctx, inject) => {
+  ctx.$moment = moment
+  inject('moment', moment)
+}

* Sorry, not tested.