Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david001's avatar

vue 3 change option api to composition API

Hi, I am changing my option API to composition API and I am stuck here with watch property of vuejs. Actually I am not sure how to get query params in vue3 composition API with script setup.

Option API : This is my part of my old script and it works

watch: {
    $route(to, from) {
    if (this.$route.query.preference == "wfh") {
        const { place, ...to } = this.$route.query;
            this.$router.replace({ query: to });
            //this.$router.replace({query: {'my_query': 1}});
        }
    console.log(to, from);
    this.getTopics(this.$route.query);
},

Now I tried to change above code as below and I got error: route is not a function

composition API: script setup

import { useRoute } from 'vue-router'
const route = useRoute()
watch(
() =>
    route((to, from) => { //got error here
        if (route.query.preference == "wfh") {
            const { place, ...to } = route.query;
            // $router.replace({ query: to });
        }
        console.log(to, from);
        getTopics(route.query);
    },
))

I also want to change this watch property to composition API:

watch: {
    filter: {
        handler() {
            const query = this.filter;
            this.$router.push({
                query: query,
            });
        },
        deep: true,
    },
},

any help would be greatly appreciated

0 likes
2 replies
MohamedTammam's avatar
import { onBeforeRouteUpdate } from 'vue-router';

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

onBeforeRouteUpdate(async (to, from) => {
     if (to.query.preference == "wfh") {
        const { place, ...to } = route.query;
        router.replace({ query: to });
     }
    console.log(to, from);
    this.getTopics(route.query);
})

https://router.vuejs.org/guide/advanced/composition-api.html#navigation-guards

watch(() => filter, (val, prevVal) => {
		const query = this.filter;
        router.push({
                query: query,
        });
})

https://vuejs.org/api/reactivity-core.html#watch

1 like

Please or to participate in this conversation.