0

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
Di Dai
  • 1
  • 1
  • 1
  • why you need that? It's really strange. Maybe you could just use Vuex instead to keep this key (or whatever it is) – Marek Urbanowicz Feb 14 '17 at 12:57
  • 1
    you may be able to do it, with the help of this page : https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/2 and with `router.beforeEach` navigation guard, doc: https://router.vuejs.org/en/advanced/navigation-guards.html – nicolast Feb 14 '17 at 18:12
  • but it looks like the perfect use case for a cookie (if you need the adtag on the backend) or local storage (if you only need adtag on the frontend) – nicolast Feb 14 '17 at 18:13
  • @nicolast is right on. You can use router.beforeEach to check for the query string and append it if it isn't there with something like this: http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter – retrograde Feb 14 '17 at 22:38

1 Answers1

3

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
CenterOrbit
  • 5,371
  • 1
  • 22
  • 34