26

i am new to Vue JS, i must say i really love this platform. I started using it just 3 days back. I am just trying to get the URL query parameter and i am using vue-router as well. Here is how i have it:

http://localhost:8001/login?id=1

Here is how my controller look like.

<template>
    <section class="contact-info-area">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <section class="write-massage-area">
                        <div class="mb-5"></div>
                        <div class="row justify-content-center">
                            <div class="col-lg-5">
                                <div class="write-massage-content">
                                    <div class="write-massage-title text-center">
                                        <h3 class="title">Login {{ $route.query.id }}</h3> <!-- THIS IS WORKING -->
                                    </div>
                                    <div class="write-massage-input">
                                        <form @submit.prevent="onSubmitForm">
                                            <div class="row">
                                            
                                                <div class="col-lg-12">
                                                    <div class="input-box mt-10">
                                                        <input type="text" placeholder="Email"  v-model="form['email']">
                                                        <ErrorMessage :validationStatus="v$.form.email"></ErrorMessage>
                                                    </div>
                                                </div>
                                                <div class="col-lg-12">
                                                    <div class="input-box mt-10">
                                                        <input type="text" placeholder="Password"  v-model="form['password']">
                                                        
                                                    </div>
                                                </div>
                                                <div class="col-lg-12">
                                                    <div class="input-box mt-10 text-center">
                                                        <button type="submit" class="main-btn main-btn-2">Login</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="mb-5"></div>
                    </section>
                </div>
            </div>
        </div>
    </section>
</template>

<script>

import { ref } from 'vue'
import useVuelidate from '@vuelidate/core'
import { required, minLength, email } from '@vuelidate/validators'
import ErrorMessage from '../components/ErrorMessage'

export default {
    name: "login",
    components: {
        ErrorMessage
    },
    created(){
    },
    setup(){
        const form = ref({})

        const rules = {
            form: {
                email: {
                    required,
                    email
                },
                password: {
                    required,
                    minLength : minLength(5)
                }
            }
        }
        const v$ = useVuelidate(rules, { form })


        function onSubmitForm(){
            console.log(this.$route.query.id) **<!-- THIS IS NOT WORKING -->**
            v$.value.$touch()
            console.log(form.value)
        }

        return { form, onSubmitForm, v$}
    }
    
}
</script>

here on the above code. On button submit i am going to a function called onSubmitForm, there i am using console.log(this.$route.query.id) but this is giving a below error :

Uncaught TypeError: Cannot read property 'query' of undefined
    at Proxy.onSubmitForm (Login.vue?a55b:84)

Why this is happening? I am seeing that in the vue document as well, they mentioned in the same way. What i am missing in this?

Thank you!

2
  • Inside setup method, this won't be available, that's why you're seeing this error. you need to do some work around to get the route params. you can try this link, it has many example for injecting route github.com/vuejs/rfcs/issues/70 Commented Oct 7, 2020 at 11:30
  • I also tried in created method as well. But there also i can not see. Also i tried with context.root.$route but then also its not working for me. Commented Oct 7, 2020 at 11:32

6 Answers 6

52

You can call useRoute to access the query params...

<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
console.log(route.query)
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, i dont know, why this simple thing was so difficult to find any where on Vue document.
Just in case it helps anyone it seems that there's two objects that you can obtain from 'vue-router'. 'useRoute' is for contains the query and represents the current route. 'useRouter' represents the actual router and can be used for navigation (like 'push()')
11

Bit late but if you want query params to work on page refresh you have to wait for the router to get ready as its asynchronous. The router wont be ready if its a page refresh. The router will be ready if its navigation from another page in that case the query params will be available from the begining.

<script setup>
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

//just to demonstrate
console.log(route.query)
// If it is a page refresh it will print null.
// The router wont be ready if its a page refresh. In that case the query wont be available.
// The router will be ready if its navigation from another page in that case the query params will be available

onMounted(() => {
  getUrlQueryParams()
});

getUrlQueryParams = async () => {    
  //router is async so we wait for it to be ready
  await router.isReady()
  //once its ready we can access the query params
  console.log(route.query)
});
</script>

Comments

5

If you use parameters and your endpoint looks something like this:

{
  path: '/inspect_detail/:id',
  name: 'inspect_detail',
  component: function() {
    return import ( '../views/Inspect_detail.vue')
  },
  params: true
},

and you are routing like this:

<router-link :to="{ name: 'inspect_detail', params: { id: akey }}">...</router-link>

then you can pickup the values like this:

<script>
import { useRoute } from 'vue-router';
export default {
  setup(){
    const route = useRoute()
    console.log( route.params );
  }
}
</script>

Comments

1

To me, to get query params from the route after doing a push

this.$router.push({ 
    name: 'shopBellaProduct', 
    query: { 
       idProduct: productId,
    }
});

I need to call this:

mounted(){

   // Get an id product from query.
   this.idProduct = this.$route.query.idProduct;
},

Note: I have to instantiate and use the router before (I'm using "vue-router 4.0.13"):

// Vue Router.
import { createRouter } from 'vue-router'

//Create the router instance.
const router = createRouter({
  routes,
})

app.use(router)

Comments

0

I hadn't done frontend in a couple of months and had to refresh on Vue 3 and route query properties, and this question came up first.

Now the memory jog has kicked in, I believe the correct way is to pass the props from the router to the component as shown in the examples here https://router.vuejs.org/guide/essentials/passing-props.html

Essentially, call your route

{
    path: "/login",
    name: "Login",
    props: route => ({ id: route.query.id }),
    component: () => import(/* webpackChunkName: "login" */ "../views/Login.vue"),
},

to be able to access the id field.

Alternately, you can sent the whole lot with props: route => ({ query: route.query })

Pick it up as a prop in your view/component

export default {
    name: "login",
    components: {
        ErrorMessage
    },
    created(){
    },
    props: {
        id: {
            type: String,
            default: "",
        }
    }
    setup(props){
        const form = ref({})

        const rules = {
            form: {
                email: {
                    required,
                    email
                },
                password: {
                    required,
                    minLength : minLength(5)
                }
            }
        }
        const v$ = useVuelidate(rules, { form })


        function onSubmitForm(){
            console.log(props.id)
            v$.value.$touch()
            console.log(form.value)
        }

        return { form, onSubmitForm, v$}
    }
}

Comments

0

difference is between using Options or composition API in vue.. i guess you can use the userRouter/useRoute in the Composition API and this.$route.query in the options API. i wonder at times why the 2 ways :/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.