Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  151] [ 4]  / answers: 1 / hits: 6193  / 4 Years ago, sun, august 16, 2020, 12:00:00

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


More From » vue.js

 Answers
1

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!"


[#2875] Thursday, August 13, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Jul 12, 20, 00:00, 4 Years ago
;