VueJs + Vite + VueRouter:无法在 setup() 中获取当前路由(尽管有很多教程展示了如何做到这一点)

问题描述 投票:0回答:1

我有一个 vite (4.4.5) / vue (3.3.4) / vue-router (4.2.5) 问题。 我尝试根据我的 vue 路由器检测当前哪个子页面处于活动状态。

有很多教程和 stackoverflow 帖子(如here)可以回答这个问题。 不幸的是,在尝试了大约 30 种不同的方法之后,我仍然陷入困境:无论我尝试什么,当我尝试在“setup()”中检测我所在的路线时,我总是得到“未定义”。

更奇怪的是,当我将 {{ $router.currentRoute }} 放入 html body 中时,我确实看到了一个包含路由的 json 。

作为一个例子,我使用了这种方法,这似乎对很多人都有效(其他 stackoverflow 线程和其他网站建议几乎所有相同的方法)。

使用以下代码(基于上述方法),我在控制台中没有得到任何响应,在 setup() 中计算的部分的 UI 上也没有得到任何响应。我已在代码中注释了相应的答案(或缺少答案)。

我已经无计可施,希望得到任何指点。

谢谢大家的宝贵时间。

<!-- testpage6.vue -->
<script lang="ts">
import { defineComponent, computed, watch } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
  name: 'MyCoolComponent',
  setup() {
    const route = useRoute();  
    console.log('This passes'); // Shows 'This passes' in console
    console.debug('current route name on component setup init: ${route.name}'); // Does not show up in console
    watch(() => route.name, () => {
      console.debug('MyCoolComponent - watch route.name changed to ${route.name}'); // Does not show up in console
    });   
    return { route };
  },
});
</script>

<template>
  <p>Current route name v1: {{ route.name }}</p> <!--  SHOWS NOTHING -->
  <p>Current route name v2: {{ $router.currentRoute }}</p> <!--  SHOWS A JSON -->
</template>

routes.js:

import { createRouter, createWebHistory } from 'vue-router'

import main     from '../layouts/MainLayout.vue'
import search   from '../pages/search.vue'
import download from '../pages/download.vue'
import history  from '../pages/history.vue'
import test1    from '../pages/testpage1.vue'
import test2    from '../pages/testpage2.vue'
import test3    from '../pages/testpage3.vue'
import test4    from '../pages/testpage4.vue'
import test5    from '../pages/testpage5.vue'
import test6    from '../pages/testpage6.vue'

const routes = [
  {
    path: '/',

    component: main,

    children: [
      {path: '/', component: search},
      {path: '/search', component: search},
      {path: '/download', component: download},
      {path: '/history', component: history},      
      {path: '/test1', component: test1},
      {path: '/test2', component: test2},
      {path: '/test3', component: test3},
      {path: '/test4', component: test4},
      {path: '/test5', component: test5},
      {path: '/test6', component: test6}
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
export default router

用户界面显示如下:

Current route name v1:

Current route name v2: { "fullPath": "/test6", "path": "/test6", "query": {}, "hash": "", "params": {}, "matched": [ { "path": "/", "meta": {}, "props": { "default": false }, "children": [ { "path": "/", "component": { "sockets": {}, "methods": {}, "__hmrId": "3a1c5473", "__file": "/vite-vue-flask-sqlite/src/pages/search.vue" } }, { "path": "/search", "component": { "sockets": {}, "methods": {}, "__hmrId": "3a1c5473", "__file": "/vite-vue-flask-sqlite/src/pages/search.vue" } }, { "path": "/download", "component": { "props": {}, "sockets": {}, "methods": {}, "__hmrId": "3d81c64d", "__file": "/vite-vue-flask-sqlite/src/pages/download.vue" } }, { "path": "/history", "component": { "props": {}, "__hmrId": "5b08ab79", "__file": "/vite-vue-flask-sqlite/src/pages/history.vue" } }, { "path": "/test1", "component": { "props": {}, "__hmrId": "f82ebe6a", "__file": "/vite-vue-flask-sqlite/src/pages/testpage1.vue" } }, { "path": "/test2", "component": { "props": {}, "__hmrId": "2e9fc06a", "__file": "/vite-vue-flask-sqlite/src/pages/testpage2.vue" } }, { "path": "/test3", "component": { "props": {}, "methods": {}, "__hmrId": "8769e246", "__file": "/vite-vue-flask-sqlite/src/pages/testpage3.vue" } }, { "path": "/test4", "component": { "props": {}, "__hmrId": "42d657e3", "__file": "/vite-vue-flask-sqlite/src/pages/testpage4.vue" } }, { "path": "/test5", "component": { "props": {}, "__hmrId": "96d3e88c", "__file": "/vite-vue-flask-sqlite/src/pages/testpage5.vue" } }, { "path": "/test6", "component": { "name": "MyCoolComponent", "__hmrId": "9a8b85d5", "__file": "/vite-vue-flask-sqlite/src/pages/testpage6.vue" } } ], "instances": { "default": { "leftDrawerOpen": true, "link": "test6", "$socket": {} } }, "leaveGuards": { "Set(0)": [] }, "updateGuards": { "Set(0)": [] }, "enterCallbacks": {}, "components": { "default": { "__hmrId": "22686b16", "__file": "/vite-vue-flask-sqlite/src/layouts/MainLayout.vue" } } }, { "path": "/test6", "meta": {}, "props": { "default": false }, "children": [], "instances": { "default": null }, "leaveGuards": { "Set(0)": [] }, "updateGuards": { "Set(0)": [] }, "enterCallbacks": {}, "components": { "default": { "name": "MyCoolComponent", "__hmrId": "9a8b85d5", "__file": "/vite-vue-flask-sqlite/src/pages/testpage6.vue" } } } ], "meta": {}, "href": "/absproxy/3000/test6" }

更新: 根据反馈,我没有将代码添加到子组件中,而是添加到主组件中。然后,我仍然没有得到有效的结果,见下文:

 <!-- MainLayout.vue -->
 setup () {
    const leftDrawerOpen = ref(false);
    const route = useRoute();  
    
    const path = computed(() =>route.path)
    console.log(path) ; // Shows 'ComputedRefImpl {dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, _setter: ƒ, …}''
    
    
    console.debug('current route name on component setup init: ${route.path}'); // Does not show up in console
    watch(() => route.path, () => {
      console.debug('MyCoolComponent - watch route.name changed to ${route.path}'); // Does not show up in console
    });   
    return {
      route
    }
  }
vue.js vuejs3 vue-router vite vue-router4
1个回答
0
投票

这是最终的解决方案:

<!-- MainLayout.vue -->
...
<script lang="ts">
import { watch } from 'vue';
import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();  
    console.debug(`${route.path}`); // Shows current route, i.e. /test6 when navigating to test6
    watch(() => route.path, () => {
      console.log(`${route.path}`) // Shows changes in router when this code block is in main component
    });   
    return {
      route,
    }
  },
}
</script>

路由器.js:

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    name: 'base',

    children: [
      {path: '/',         component: () => import('../pages/search.vue'), name: 'home',},
      {path: '/search',   component: () => import('../pages/search.vue'), name: 'search'},
      {path: '/download', component: () => import('../pages/download.vue'), name: 'download'},
      {path: '/history',  component: () => import('../pages/history.vue'), name: 'history'},      
      {path: '/test1',    component: () => import('../pages/testpage1.vue'), name: 'test1'},
      {path: '/test2',    component: () => import('../pages/testpage2.vue'), name: 'test2'},
      {path: '/test3',    component: () => import('../pages/testpage3.vue'), name: 'test3'},
      {path: '/test4',    component: () => import('../pages/testpage4.vue'), name: 'test4'},
      {path: '/test5',    component: () => import('../pages/testpage5.vue'), name: 'test5'},
      {path: '/test6',    component: () => import('../pages/testpage6.vue'), name: 'test6'}
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
export default router

<p>Current route: {{ route.path }}</p> <!--  Current route: /test6 -->

在 UI 上显示路线。

对我有帮助的是这个例子

© www.soinside.com 2019 - 2024. All rights reserved.