简体   繁体   中英

How to access plugin from nuxt.js store?

I have this gtag (analytics plugin) that I can access on my components but never on my store. I would appreciate any opinions. Thanks

plugins/vue-gtag.js

import Vue from "vue"
import VueGtag from "vue-gtag"

export default ({ app }, inject) => {
  Vue.use(VueGtag, {
    config: {
      id: process.env.ga_stream_id
    }
  })
}

store/gaUserProperty.js

import Vue from "vue"
import { User } from "~/models/user/User"

export const states = () => ({})

const getterObjects = {}
const mutationObjects = {}
Object.keys(states).forEach(key => {
  getterObjects[key] = state => state[key]
  mutationObjects[key] = (state, value) => (state[key] = value)
})

export const state = () => states

export const getters = { ...getterObjects }

export const mutations = { ...mutationObjects }

export const actions = {
  async sendUserProperties({ dispatch, commit }) {
    let res = await this.$UserApi.getUser()
    if (!(res instanceof User)) {
    } else {
      // I can access this on my components and pages but for some reason not here....
      console.log(this.$gtag)
    }
  }
}

To import this properly, I would export the instance (or any of its internals) from main.(ts|js) :

const Instance = new Vue({...whatever});

// only export what you need in other parts of the app
export const { $gtag, $store, $t, $http } = Instance;

// or export the entire Instance
export default Instance;

now you can import it in your store:

import Instance from '@/main';
// or: 
import { $gtag } from '@/main';

// use Instance.$gtag or $gtag, depending on what you imported.

As other answers mentioned, in current Vuex version the Vue instance is available under this._vm inside the store. I'd refrain from relying on it, though, as it's not part of the exposed Vuex API and not documented anywhere. In other words, Vuex developers do not guarantee it will still be there in future versions.
To be even more specific, Vue's promise is that all v2 code will work in v3 . But only if you use the exposed API's.

And the discussion here is not even on whether it will be removed or not (it most likely won't). To me, it's more a matter of principle: if it starts with a _ and it's not documented, it translates into a message from authors: "We're reserving the right to change this at any time, without warning!"

You can access the Vue instance through this._vm in the Vuex store, so you would just need to do:

console.log(this._vm.$gtag)

That should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM