Vladimir  Golub
Vladimir Golub

Reputation: 613

How to get access to Vue.prototype in asyncData?

In plugin, I add new property to Vue prototype.

import Vue from 'vue';
import { DateTime } from 'luxon';

Object.defineProperty(Vue.prototype, '$DateTime', { value: DateTime });

I want to use it in asyncData, how to get access?

async asyncData(context) {
  context.store.commit('calendar/setSelectDate', $DateTime.now());
}

Upvotes: 2

Views: 657

Answers (2)

Lovlesh
Lovlesh

Reputation: 832

import Vue from 'vue';
async asyncData(context) {
  context.store.commit('calendar/setSelectDate', Vue.prototype.$DateTime.now());
}

Upvotes: 1

kissu
kissu

Reputation: 46696

I'm not sure that defineProperty is the way to go here. You could maybe inspect the Vue instance itself and see if there is some $DateTime on it, if it is, a context.$DateTime should do the trick.

If it's not working with context.$DateTime, maybe try it when your component is mounted in a regular this.$DateTime on a button click, for debugging purposes.


Using regular Nuxt plugins or even inject is a more clean and Vue-y way of doing things.

import { DateTime } from 'luxon'
export default ({ app }, inject) => {
  inject('DateTime', DateTime)
}

then

async asyncData({ store, $DateTime }) {
  store.commit('calendar/setSelectDate', $DateTime.now())
}

or from components/pages

this.$DateTime.now()

Speaking of Vue, you don't want to use vue-luxon. Looks like a simple and quick way of using the library. Is it because it is not mantained for already 7 months or something else?

Upvotes: 2

Related Questions