"Unleashing the power of plugins in your Nuxt.js store: A step

I am facing an issue with my gtag (analytics plugin) where I can access it on my components but not on my store. Any suggestions are welcome. Thank you.

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 {
      // While I can access this in other places, for some reason, I cannot access it here....
      console.log(this.$gtag)
    }
  }
}

Answer №1

If you want to properly import this, you should export the instance (or any of its internal components) from main.(ts|js):

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

// only export what is needed in other parts of the application
export const { $gtag, $store, $t, $http } = Instance;

// or export the entire Instance
export default Instance;

Now you can import it into your store:

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

// utilize Instance.$gtag or $gtag depending on what you imported.

As pointed out by other responses, in the current version of Vuex, the Vue instance can be accessed using this._vm within the store. However, relying on this is not recommended as it is not part of the documented Vuex API and may change in future versions.
To be more specific, Vue promises that all code written for v2 will function in v3, but only if using the officially exposed APIs.

The conversation here isn't necessarily about whether this feature will be removed (it likely won't). For me, it's a matter of principle: if it begins with an underscore and lacks documentation, it sends a clear message from the creators: "We reserve the right to modify this at any time, without notice!"

Answer №2

To retrieve the Vue instance within the Vuex store, access it using this._vm. You can then easily log the value like this:

console.log(this._vm.$gtag)

This simple solution should work for you.

Answer №3

As per nuxtjs, the plugins can be accessed in the store actions.

https://nuxtjs.org/docs/directory-structure/plugins

At times, there is a need to share functions or values throughout your application. These variables can be injected into Vue instances (client side), context (server side), and even in the Vuex store. It is recommended to prefix these functions with a $ sign for convention.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Restrict Recursive GraphQL Schema Query Depth with graphql-sequelize resolver in Node.js using express-graphql

In my code, I have two models called User and Post. My goal is to retrieve User information when querying a post, as well as obtain all of a User's posts when querying a user. These two models are associated in the following manner: User.hasMany(Pos ...

Tips on refreshing the D3 SVG element following updates to the dataset state in a React application

Hey everyone, I'm currently experimenting with D3.js and React in an attempt to build a dynamic dancing bargraph. Can anyone provide guidance on how to reload the D3 svg after updating the dataset state within REACT? Feel free to check out my codepen ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Converting jQuery into Methods within a VueJS function

How can I implement this function as a method in VueJS? $(document).ready(function(){ $(".slide").hover(function(){ $(this).find("div.snipit").slideDown("slow"); },function(){ $(this).find("div.snipit").slideUp("slow"); ...

Angular 14 - Issue with passing values through props - Error: Uncaught (in promise): InvalidCharacterError occurs when attempting to set attribute with 'setAttribute' method

I am a beginner with Angular and encountering an issue when trying to pass props from a parent component to a child component. The specific error I am facing is related to an invalid attribute name while using Angular version 14.2.5. core.mjs:7635 ERROR ...

Retrieve information from a JSON document

My project involves a bookStore with a list of books that I am working on. I am trying to extract all the book data from a JSON file and display them in a card view on a webpage. Although my code is error-free and seems to be functioning properly, the da ...

NextJS rendering props in a loop

I need help figuring out how to render props in a loop using the forEach function. This is my current code: {console.log('the catalog inside the component ----->', catalog)} {Object.keys(catalog).forEach(key => { return ( <d ...

Leverage Node.js to access an array from app.js within a module

Within my Node app.js file, I am looking to make my array openConnections accessible by the module sse_server.js for the sseStart function. How can I achieve this without necessarily declaring the array as a global variable in app.js? Here is a snippet of ...

Recreating elements in ng-repeat using ng-click conditionally

I am attempting to swap an anchor tag with an image when clicked by the user. The code snippet I'm using looks like this: <div ng-repeat="postpart in currentPost.parts "> <div ng-if = "!postpart.isclicked"> <img ng-src= ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...

Modifying the class of an HTML element using JavaScript

Is it possible to dynamically change the class of an HTML element based on a user's selection with a radio button? I am facing an issue where I receive the following error message: "Error: missing ) after argument list Source File: website Line: 1, C ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

An External Force is Disrupting My Jquery

Something seems off because everything was working perfectly fine until the FallingLeavesChristmas.min.js file stopped activating on this specific page. I initially thought it was an issue with the JavaScript itself, but that doesn't seem to be the ca ...

Empty text box

I've been attempting to clear ng-model inputs, but haven't had any success and I can't seem to figure out why. Here is what I have: <button ng-click="$ctrl.clear()"></button> And in the clear action, I have: $scope.$event = n ...

A guide on loading theme JavaScript files in Next.js

I am planning to incorporate a theme from themeforest into Next.js Despite my attempts, I encountered issues with loading jquery core and certain plugins in Nextjs. import { useEffect } from "react" import { SessionProvider } from "next-aut ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

Develop a custom npm package with dependencies stored locally and add it to a different package during installation

I have developed three unique custom modules. getcorrespondence-1.0.0.tgz getrediscache-1.0.0.tgz setrediscache-1.0.0.tgz These custom node modules were created using the command npm pack. The module getcorrespondence-1.0.0.tgz has dependencies on two o ...

BlurDataURL for Data URLs in Next.js

NextJS 11 brings the exciting feature of using the Image component with a blur placeholder. To utilize this with dynamic images, we need to make use of the blurDataURL, which is a Data URL. I am interested in taking my original image and resizing it to a ...