Monday 25 September 2023

Vue 3 shows previous route in onMounted

I'm using Vue with a dynamic navigation based on my backend. An endpoint decides what page to display based on the current route.

I've made a simplified version below with the relevant parts. Everything works fine, except for when I use a <router-link> or router.push to one of my routes. In the onMounted callback of my target page, the route seems to be the previous route (see AboutView.vue below).

I've tried await router.isReady(), but as far as I can tell it's not relevant here, it's only used for an initial page view.

Sample repo built with node 16.13.2: https://github.com/tietoevry-johan/vue-routing

App.vue

<template>
  <router-view/>
</template>

router.ts

export const currentPage = ref('HomeView')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      name: "PageSelector",
      path: "/:catchAll(.*)",
      component: PageSelector
    }
  ]
});

router.beforeEach(async (to, _, next) => {
  currentPage.value = await getComponentByPath(to.path)
  next()
})

async function getComponentByPath(path: string) {
  return path === '/' ? 'HomeView' : 'AboutView'
}

PageSelector.vue

<template>
  <component :is="currentPage" />
</template>

<script lang="ts">
import { defineComponent } from "vue"
import AboutView from "@/views/AboutView.vue"
import HomeView from "@/views/HomeView.vue"
import { currentPage } from "@/router"

export default defineComponent({
  // eslint-disable-next-line vue/no-unused-components
  components: { HomeView, AboutView },
  setup() {
    return {
      currentPage
    }
  }
})
</script>

AboutView.vue

<template>
  about
</template>

<script lang="ts">
import router from "@/router";
import { defineComponent, onMounted } from "vue";

export default defineComponent({
  setup() {
    onMounted(() => {
      console.log(router.currentRoute.value?.fullPath) // prints / instead of /about
      // when clicking a router link or router push to this page
    })
  }
})

</script>


from Vue 3 shows previous route in onMounted

No comments:

Post a Comment