Home > Mobile >  Why is a route not reactive?
Why is a route not reactive?

Time:06-10

As part of my Quasar app, I have the following route:

import { RouteRecordRaw} from 'vue-router'
import { uid } from 'quasar'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: () => {
      console.log('matched /')
      return {path: `/${uid()}`}
    }
  },
  {
    path: '/:uuid',
    component: () => import('pages/User.vue')
    // component: User,
  },
];

export default routes;

This works fine when going to /: the URL is changed to /73a219e5-2cf2-4dd0-8... and User.vue is executed (specifically there a fetch inside that retrieves some data based on the :uuid parameter.

If I force a route from within a component (User.vue for instance), via

import { useRouter } from 'vue-router'

const router = useRouter()
router.push('/')

I do see that the URL changes to a new UUID but User.vue is not executed. Specifically, a reference to route.params.uuid where const route = useRoute() is not reactive.

Is this normal (= I have to look for anther way to trigger), or is there a misuse (erroneous use) on my side?

CodePudding user response:

The core of the issue is that you're (re)using the same component for rendering the page you're navigating from and the page you're navigating to.

By design, Vue optimises DOM rendering and will reuse the existing component instance. This means certain hooks won't be triggered (e.g: mounted, created, etc...) when changing route.

To force Vue into creating a different component instance when the route changes, use the current route's .fullPath as key on <router-view>:

<template>
  ...
  <router-view :key="route.fullPath"></router-view>
  ...
</template>
<script setup>
import { useRoute } from 'vue-router'

const route = useRoute();
</script>
  • Related