What is the method for accessing the Vue object in a Vuex module?

When working with Vue components, it's simple to utilize imported libraries like vue-router. I can easily retrieve the necessary route parameter using this.$route.params.myVar. However, when attempting to do the same within a Vuex module, an error occurs:

TypeError: Cannot read property 'myVar' of undefined
. How can I extend the Vue object I defined in my main.js to my modules?

Below is my main.js:

import router from './router'
import Vuex from 'vuex'
import myModule from './my.module';

Vue.use(Vuex)

// Register VueX modules
const store = new Vuex.Store({
  modules: {
    myModule
  }
})

new Vue({
  router,
  render: h => h(App),
  store
}).$mount('#app')

And here's my my.module.js:

export default {
  namespaced: true,
  state: {
    ...
  },
  mutations: {
    ...
  },
  actions: {
    someAction() {
      console.log(this.$route.params.myVar)
    }
  }
}

It becomes apparent that this is not defined. Attempts were made to instantiate a new Vue object at the beginning of the module:

var vm = new Vue()

However, changing this to vm resulted in a similar error:

Cannot read property 'myVar' of undefined
. Another effort involved re-instantiating the route class within the module:

import route from 'vue-router'

Adapting the code to route.params.myVar still led to the error message:

Cannot read property 'myVar' of undefined
.

Answer №1

In my opinion, there are two possible solutions available to you.

  • Transfer param.myvar from an external source to the vuex action
  • Incorporate the router into the vuex module and utilize it

If you choose the second option, ensure that you import the specific router declaration rather than the entire library. For instance:

import router from '@/router'

router.currentRoute.params.myVar

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

Using components from other modules in a sibling module's component in Angular 4

Let me provide some context - I'm currently working with Angular 4 and the AngularCLI. The structure of my folders looks like this: app helper-components helper-components.module.ts views admin admin.module.ts views.m ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

Filtering out elements from an array using jQuery

I am looking for an efficient way to maintain an array of elements by adding and removing arrays of elements dynamically. var myElements = $('.initial'); Instead of creating a new array, jquery's merge() allows me to add items to the exist ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

What strategies can I employ to prevent redundancy when all my .vue files are identical?

Although I am new to Vue, there are many aspects that I find appealing. However, one thing I dislike is combining templates, scripts, and styles in the same file. Instead, I prefer separating these concerns by using: <template src="./template.html"> ...

Revamping jQuery for a React component

As I transition away from using jQuery for quick hides, shows, and CSS changes in favor of React components that require re-rendering without triggering the jQuery actions requiring a page refresh, I find myself needing to set state within each component. ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

Ways to parse a JSON array using Javascript in order to retrieve a specific value if it is present

Below is the JSON code stored in an array: { "kind": "urlshortener#url", "id": "http://goo.gl/2FIrtF", "longUrl": "http://hike.com/?utm_source=facebook", "status": "OK", "created": "2015-09-22T13:45:53.645+00:00", "analytics": { "allTime": { ...

Using React to dynamically assign a backgroundImage based on a JSON response

I am having an issue with retrieving data from my Wordpress API and displaying it in my react app. Specifically, I am struggling to set the post's featured image as a background-image for an element. Here is an example of the JSON response: { "id" ...

Executing JQuery asynchronous calls sequentially

Recently delving into the world of Jquery, I've encountered a coding challenge: my code loops through an array and retrieves HTML from an ajax request for each iteration. $.each(arr, function (data) { $.get('/Quote/LoadQuoteItemCost', { ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

Executing a ternary expression prior to confirming null values

Is it possible to shorten the code below using a ternary expression? if(paginator) { paginator.pageIndex = 1; } I attempted this: paginator.pageIndex = paginator ? 1 : undefined However, I am uncertain if this is the best approach or if there is a mo ...

What is the best way to create a DOM element listener in AngularJS?

My goal is to monitor a <div id="please_monitor_me"> to determine if it is visible. If it is not visible, I plan to remove the margin (margin: 0;). I am aiming for no margin when the div is not visible so that it can be shown later with a burger but ...

Adding a firebase-messaging-sw.js file to Bubble? [UPDATE - file not compatible]

While troubleshooting an error message, I came across a common resolution that suggests adding a firebase-messaging-sw.js file. However, since I am using a bubble HTML element to run the script, I am unsure about the proper way to do this. I attempted usin ...

Transferring information via a TCP socket in Node.js from an HTML webpage

Hey there! I'm curious about net sockets in Node.js and would love some clarity: I've set up a simple server that echoes back received data. Here's the code: var net = require('net'); var HOST = '127.0.0.1'; var PORT = ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Creating a JSON file that contains a collection of discord.js statuses and then seamlessly integrating it into the primary JavaScript document

const userActivities = [ { name: "Morning Jog", type: ActivityType.Running }, { name: "Afternoon Nap", type: ActivityType.Sleeping }, { name: "Evening Game Night", type: ActivityType.Gaming }, { name: "Late Night Code ...

JSGrid not displaying any information from the JSON source

Hello! I'm currently working on customizing the "DataManipulation" example from jsGrid demos, but I'm facing a challenge in displaying data fetched from a JSON file using a GET AJAX call. Below is my controller code: { loadData: ...