4

I'm having an issue getting the URL query string from within a component. I am trying to implement this https://router.vuejs.org/guide/essentials/passing-props.html#function-mode so I can pass the query as a prop. I haven't used query strings much, and I tend to use params, but I need the query string in this case. The problem I am having is mounted() doesn't seem to have access to the query.

Below is a basic sample of what I can't get working:

URL = http://localhost:8080/?q=This%20is%20my%20query

Router.js

{ path: '/', component: () => import('./App.vue'), props: (route) => ({ query: route.query.q }) } 

App.vue (Excerpt)

<template> <div id="app"> 1.{{ $route.query }} 2.{{ query }} <searchResults class="results"/> </div> </template> props: ['query'], mounted () { console.log(this.query) console.log(this.$route.query) }, 

In the code above, the following happens on visiting the URL in question:

console.log(this.query) = undefined

console.log(this.$route.query) = undefined

In the template, the following is output:

1.{} 2. 

What do I need to do to get the query passed as the prop correctly?

9
  • Is using query string as prop actually necessary? I mean, isn't that enough to access the query string plainly as suggested here? Commented Sep 6, 2018 at 10:25
  • Yes true, but I have had issues with that as well as detailed here. stackoverflow.com/questions/52201770/… so I thought passing it as a prop might help Commented Sep 6, 2018 at 10:28
  • Did you try within other lifecyle hooks than mounted (or maybe in mounted, but wrapped within nextTick)? Commented Sep 6, 2018 at 10:36
  • Yes, I tried mounted and created. Commented Sep 6, 2018 at 10:38
  • Here's a demo of vue-router's props-function: codesandbox.io/s/yv5410xlmz Commented Sep 6, 2018 at 11:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.