Home > Software engineering >  Vue.js - Define path of vue route based on URL query params
Vue.js - Define path of vue route based on URL query params

Time:06-24

Let's assume I have this URL http://localhost:8080/public/form?code=fhuZ15aHy

I have defined a route in my route.js file like this

{ 
  path: '/public/form?code=:code',
  name: 'survey',
  component: () => import('./views/form')
}

which is supposed to reuse the same component based on the code query parameter coming from URL.

In my form.vue component I have defined a prop like this:

props: {
   code: {
       type: String,
       required: true
   }
}

But this is not working, in the sense that I am not redirected to any page.

I think I'm doing wrong with how I defined the path of the route. How can I achieve this?

CodePudding user response:

Do not define the query within the path

You should write like this:

{ 
  path: '/public/form',
  name: 'survey',
  component: () => import('./views/form')
}
router.push({ path: '/public/form', query: { code } })

And within the component you can access the query like this

const {code} = this.$route.query
  • Related