Home > Blockchain >  Composition API | Vue route params not being watched
Composition API | Vue route params not being watched

Time:09-18

I have pretty much the same example from the docs of watch and vue router for composition API. But console.log is never getting triggered even though the route.params.gameId is correctly displayed in template

<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
const store = useStore()
const route = useRoute()

watch(
      () => route.params.gameId,
      async newId => {
        console.log("watch" newId)
      }
    )
</script>

<template>
    <div>
        {{route.params.gameId}}
    </div>
</template>

What am I doing wrong? I also tried making watch function non async but it didn't change anything and later on I will need it for api fetching so it should be async.

CodePudding user response:

You should add immediate: true option to your watch :

watch(
      () => route.params.gameId,
      async newId => {
        console.log("watch" newId)
      },
      { 
          immediate: true

      }
    )

Because the watch doesn't run at the first rendering while the params is changes only one time at the page load, So the watch misses that change.

  • Related