3

How can I keep params while navigating through routes. The parameter/parameters have to be in every page of the application (not only in nested routes). In angular I can do this with this._router.navigate([''], { queryParamsHandling: 'merge' }), but how can I do it with vue.js?

Example of base routes:

// base route 1 -> http://example.test/?user_code=1234&member=false
// base route 2 -> http://example.test/?user_code=56789&member=false
// base route 3 -> http://example.test/?user_code=4321

How can I keep the parameters user_code and member in every route I navigate?

Example of what I want

// navigated route 1 -> http://example.test/about?user_code=1234&member=false
// navigated route 2 -> http://example.test/whatever_page?user_code=56789&member=false
// ...

Why I need this? Because then I will need the params to do things in the app Ex: this.$route.query.user_code == '1234' ? 'do this' : 'do that';

Thank you in advance!

hailton
  • 591
  • 1
  • 3
  • 15

1 Answers1

3

A typical approach would be to use state and push the fullPath of the route into that state attribute (likely an Array).

With vuex:

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    paths: []
  },
  mutations: {
    PUSH_PATH (fullPath) {
      paths.push(fullPath)
    }
  },
  actions: {
    pushPath(commit, fullPath) {
       commit("PUSH_PATH", fullPath)  
    }
  } 
})
// in a component
import { mapActions } from "vuex";
...

  methods: {
    ...mapActions("pushPath")
  },
  created() {
    this.pushPath(this.$route.fullPath)
  }

Now if you used pushPath, when your view is created, it would add the fullPath to an array that you could later make decisions about either through injection, inspection, etc.

Another popular option, especially when making decisions based on routes is to use "Navigation Guards". These are functions that intercept the route and allow you to perform some action. More details are available here: https://router.vuejs.org/guide/advanced/navigation-guards.html

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
  • I ended up by using the 2 solutions provided by you. After setting everything in the store, I then injected the route with beforeEach guards. Got some inspiration in the reply of @CenterOrbit (user:663058) here https://stackoverflow.com/questions/42226479/how-to-hold-url-query-params-in-vue-with-vue-router – hailton Jan 05 '22 at 16:15