Accessing the current route in a Vuex module using Vue.js

I've created a vuex store with namespaces that retrieves a specific store entry based on the current route parameter.

import Router from '../../router/index'

const options = {
  routeIdentifier: 'stepId'
}

export function fetchFromRoute(state) {
  if (!options.routeIdentifier || !Router.currentRoute.params) {
    return null
  }

  return state.all.find(item => {
    return item.identifier === Router.currentRoute.params[options.routeIdentifier]
  })
}

While this function works correctly on initial load, it doesn't automatically update when the route changes.

Is there a way to force the getter to recalculate upon route change?

Answer №1

It is recommended to import the store in the router module instead of the other way around. Utilize the beforeEach navigation guard to store the current route in the store. Start by setting up the store:

store.js

state: {
  route: null
},
mutations: {
  SET_ROUTE(state, route) {
    state.route = route;
  }
},
modules: { ... }

In the router module, implement the beforeEach guard to save the current route, which is represented by the to argument:

router.js

import store from '@/store';  // Import the store in the router module

const router = new VueRouter({
  ...
})

router.beforeEach((to, from, next) => {
  store.commit('SET_ROUTE', to);
  next();
});

To retrieve this route in a Vuex module getter, access it using the third getter argument, rootState:

store/someModule.js

getters: {
  getRoute(state, getters, rootState) {
    return rootState.route;
  }
}

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

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Adjusting the hue of the Vuetify app-bar expansion

Is there a way to change the color of the v-app-bar extension separately from the v-app-bar itself? I have looked through the documentation but couldn't find any information on this. It seems like a simple customization that many people would be inter ...

There seems to be an issue with loading data for the grid from the JSON

I need some help with creating a fiddle that loads data from a json file. I'm not sure why the data is not loading properly. You can view my fiddle here: Fiddle This is my code for the data store: Ext.create('Ext.data.Store', { storeI ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

The axios library fails to send formdata to the server

Recently, I've been working on an axios code to handle form data submission. Here's the snippet of the code: updatesetting: function(){ let formData = new FormData(); formData.append('email', this.email); formData.append(&a ...

What steps can be taken to resolve the error "Incompatible types: TodoItem undefined cannot be assigned to type TodoItem"?

I am currently in the process of learning TypeScript. Here is what's inside todoItem.ts: export class TodoItem { constructor( public id: number, public task: string, public complete: boolean = false ) {} printDetails(): void { ...

Tips for resolving the error message "SyntaxError: Unexpected identifier" when conducting tests on vuetify components with jest

I've developed numerous reusable components using Vuetify. For unit testing, I'm utilizing the Jest testing framework. However, when running 'npm run test', the test fails with a 'SyntaxError: Unexpected identifier' message. ...

Retrieve the initial occurrence that meets the conditions across three columns in MySQL

I am currently utilizing a NodeJS REST API that connects to a MySQL database. Within this database, there is a specific table we will refer to as Table_01: | C_0| C_1| C_2| C_3| | 1 | A1 | B1 | 1 | | 2 | A1 | B2 | 0 | | 3 | B1 | A1 | 0 | | 4 | A2 | ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

Anticipated outcome for absent callbacks in module API implementation

I am seeking advice on the expected behavior when developing a Node module API. It is becoming complicated in my module implementation to check if the caller has provided a callback before calling it. I am starting to believe that it may be the user's ...

Having trouble getting my parallax slideshow to work with jquery preventDefault

-UPDATE- After countless hours of online courses, tutorials, and programming, I finally completed my website! Check it out here: The site is almost where I want it to be, but there are a few remaining challenges: 1) AJAX: I'm struggling to get the ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

What's the deal with receiving [object Object] in my JavaScript JSON document?

When I use console.log(values), it returns "[object Object]" instead of logging the array as expected. This is the code snippet I'm working with: let values = { "coins": 0, "griffinFeathers": 0, "souvenir": 0, "cogs": 0, "cats": 0 ...

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

Encountering a 500 internal server error or receiving an error message stating "invalid value for stripe.confirmCardPayment

I'm currently working on implementing a payment component for my React app using Stripe for the first time. Despite following a tutorial closely, I keep encountering an internal server error or receiving an "invalid value for stripe.confirmCardPayment ...