为什么路线没有反应性?

发布于 2025-02-05 22:31:41 字数 811 浏览 0 评论 0原文

的一部分

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;

作为我的:URL已更改为/73A219E5-2CF2-4DD0-8 ...user.vue(特别是fetch内部基于:UUID参数来检索一些

数据

import { useRouter } from 'vue-router'

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

。 URL更改为新的UUID,但user.vue均未执​​行。代码>不是反应性的

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2025-02-12 22:31:51

该问题的核心是您(重新)使用相同的组件来渲染您要导航的页面 以及您正在导航的页面

通过设计,VUE优化了DOM渲染,并将重复使用现有组件实例。这意味着在更改路由时不会触发某些钩子(例如:已安装,创建等...)。

要在路由更改时强迫创建不同的组件实例,请在< router-view>上使用当前路由的.fullPath作为key

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

const route = useRoute();
</script>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文