Home > Software engineering >  How to acess url GET parameter in setup() Vue 3?
How to acess url GET parameter in setup() Vue 3?

Time:01-27

This is my URL: http://localhost:8888/static/?foo=true via which Vue 3 application works.

In setup() I want to get foo parameter.

This is my code:

import { useRoute } from 'vue-router';
import { defineComponent, reactive, ref, Ref, watch, createApp, onMounted} from 'vue';

export default defineComponent({
  name: 'App',
  
  setup() {
    onMounted(() => {
        const route = useRoute();
        console.log(route);
        console.log(route.params.foo);
        console.log(route.query.foo);
    });
  },
})

And this is what I get: enter image description here

Could anyone say how to do it?

CodePudding user response:

I think that the root problem is triggering it inside the onMounted hook of the App.vue component. The route instance is probably not yet populated in that moment. You can test it by console.log-ing the route.query inside onUpdated hook. A workaround for you could be something like this:

const unwatch = watch(
  () => route.query,
  (newQuery) => {
    console.log(newQuery.foo);
    unwatch();
  }
);

Basically you would assign a watcher for the route.query and after the first update - the watcher would be destroyed.

  •  Tags:  
  • Related