Di Dai
Di Dai

Reputation: 11

How to hold URL query params in Vue with Vue-Router

I am doing a project in Vue with Vue-Router . in my project ,i have a param named 'adtag' , which must be in the url query params , is there any simple way to hold this param ,no mater how router goes.

for example , I have three pages:

  1. localhost/index
  2. localhost/list
  3. localhost/detail?id=11

page change using vue-router <router-link :to="{name:'Detail',query:{id:item.id}}"></router-link>

if I opened first page localhost/index?adtag=123 with adtag,page will changes with param 'adtag'

  1. localhost/index?adtag=123
  2. localhost/list?adtag=123
  3. localhost/detail?adtag=123&id=11

Upvotes: 1

Views: 13145

Answers (2)

Haldir
Haldir

Reputation: 1

As this is still an issue, I would even recommend using next(false) instead of returning.

if (from.query.foo && !to.query.foo) {
  if (from.path === to.path) {
    next(false);
  } else {
    next({
      path: to.path,
      query: { ...to.query, foo: from.query.foo },
    });
  }
} else {
  next();
}

For reference, the same issue from the github repository: https://github.com/vuejs/vue-router/issues/1900#issuecomment-346531301.

Upvotes: 0

CenterOrbit
CenterOrbit

Reputation: 6871

With a default Vue 2.x installation, the router file is located src/router/index.js

I was able to then check if I needed to modify the request and add in any missing query params (modifying the to var apparently has no effect), and then call a "redirect" of next( .. new rout.. ).

Downside: Doubles the route calls, because essentially it redirects

Upside: It works, and the query preserving logic is in one place.

One caveat: On page load, the router fires and the "from" is a very empty route (even excluding the query params that were in the URL). Therefor I setup that if statement to verify the need to place the query param in place.

import Vue from 'vue'
import Router from 'vue-router'
// ... All your other components

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Dashboard',
      component: Dashboard
    },
    // ... All your other routes
  ]
})

router.beforeEach((to, from, next) => {
  if (from.query.token && !to.query.token) {
    if (to.path === from.path) {
      // console.log('Identical routes detected')
      return // This is a no-no via the documentation, but a bug in routing to identical routes strips query params, and this prevents that
    }
    next({path: to.path, query: {token: from.query.token}})
  }

  next()
})

export default router

Upvotes: 6

Related Questions