使用currentRoute属性动态获取当前路径

4,986 阅读1分钟

一、前言

最近用vue3做一个管理台系统,侧边菜单栏的高亮需要和当前访问页面相匹配,这就需要监听路由的变化,动态获取当前的path并设置对应菜单项高亮。

二、方案

2.1 vue3-admin的方案

看了一下vue3-admin的实现方案是通过全局前置路由守卫router.beforeEach进行路由变化监听的:

const unwatch = router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    // 如果路径是 /login 则正常执行
    next()
  } else {
    // 如果不是 /login,判断是否有 token
    if (!localGet('token')) {
      // 如果没有,则跳至登录页面
      next({ path: '/login' })
    } else {
      // 否则继续执行
      next()
    }
  }
  state.showMenu = !noMenu.includes(to.path)
  state.currentPath = to.path
  document.title = pathMap[to.name]
})

onUnmounted(() => {
  unwatch()
})

2.2 我的方案

查看vue-router-next的文档,发现其提供了一个currentRoute只读属性,值的类型是Ref<RouteLocationNormalized>,于是想到可以利用此属性,在组件中通过computed属性动态获取当前路径。

<script lang='ts' setup>
import { computed } from 'vue'
import { useRouter } from "vue-router";

const router = useRouter()

const currentPath = computed(()=>{
    console.log('route changed',router.currentRoute.value.path)
    return router.currentRoute.value.path
})
<script>

结果是完全OK的^_^ image.png