如何从nuxt.js商店访问插件?

问题描述

我有这个gtag(分析插件),可以在我的组件上访问,但不能在我的商店中访问。 我将不胜感激。谢谢

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)
    }
  }
}

解决方法

您可以通过Vuex存储中的this._vm访问Vue实例,因此您只需要执行以下操作:

console.log(this._vm.$gtag)

应该可以解决问题。

,

要正确导入此文件,我将从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;

现在您可以将其导入您的商店:

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

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

正如其他答案所述,在当前的Vuex版本中,Vue实例在商店内部的this._vm下可用。但是,我避免依赖它,因为它不是公开的Vuex API的一部分,也没有任何文档记录。换句话说,Vuex开发人员不保证它在将来的版本中仍然存在。
更具体地说,Vue承诺所有v2代码都将在v3中工作。但前提是您使用公开的API。

这里甚至没有讨论是否将其删除(很可能不会删除)。对我来说,这更是一个原则问题:如果它以_开头且未记录在案,则会转化为作者的信息:“我们保留随时更改此内容的权利,没有警告!”