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?

tony19
  • 125,647
  • 18
  • 229
  • 307
Craig Ward
  • 2,425
  • 5
  • 33
  • 51
  • Is using query string as prop actually necessary? I mean, isn't that enough to access the query string plainly as suggested [here](https://stackoverflow.com/a/35916241/5775077)? – P3trur0 Sep 06 '18 at 10:25
  • Yes true, but I have had issues with that as well as detailed here. https://stackoverflow.com/questions/52201770/vuejs-route-not-available-on-page-load so I thought passing it as a prop might help – Craig Ward Sep 06 '18 at 10:28
  • Did you try within other lifecyle hooks than mounted (or maybe in mounted, but wrapped within nextTick)? – P3trur0 Sep 06 '18 at 10:36
  • Yes, I tried mounted and created. – Craig Ward Sep 06 '18 at 10:38
  • Here's a demo of vue-router's props-function: https://codesandbox.io/s/yv5410xlmz – tony19 Sep 06 '18 at 11:18
  • `component: () => require('./App.vue'),` shouldn't work. `require()` should be `import()` there. Is that a copy-paste error? – tony19 Sep 06 '18 at 11:55
  • Yes copy paste error. My code is more or less exactly the same as the sandbox demo @tony19 supplied. Yet, I still get undefined? – Craig Ward Sep 06 '18 at 11:58
  • `App.vue` is normally the root component. Why are you importing it dynamically? – tony19 Sep 06 '18 at 12:06
  • Why do you use "q" as parameter if the prop is called "query"? – Roel Aug 28 '20 at 08:25

0 Answers0