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

vxbzzdmp  于 2023-11-21  发布在  Vue.js
关注(0)|答案(1)|浏览(191)

我有一个vite(4.4.5)/ vue(3.3.4)/ vue-router(4.2.5)问题。我试图根据我的vue路由器检测哪个子页面当前处于活动状态。
不幸的是,在尝试了大约30种不同的方法后,我仍然被卡住了:无论我尝试什么,当我试图在“setup()”中检测我在哪条路由时,我总是得到“undefined”。
更奇怪的是,当我将{{ $router.currentRoute }}放入html主体时,我确实看到了一个包含路由的JSON。
作为一个例子,我使用了this approach,这似乎对很多人来说都很有效(其他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


以下是UI显示的内容:

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
    }
  }

8cdiaqws

8cdiaqws1#

以下是最终的解决方案:

<!-- 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>

字符串
Router.js:

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

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

    children: [
      {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上显示路线并使组件显示为活动:

:active="route.name === 'search'"


帮助我的是这个example

相关问题