vue3.0 获取本地路由

1、script:

import { onMounted,  getCurrentInstance, ref } from 'vue'

2、setup:

const { proxy } = getCurrentInstance();
或:
const { ctx } = getCurrentInstance();

3、页面加载打印:

onMounted(()=>{
  console.log(proxy);
  console.log(proxy.$router.options.routes);
});

 注:ctx 代替 this 只适用于开发阶段,生成环境需要替换成 proxy。

route.js:

import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        hidden: true,
        meta: { title: 'Home', icon: '', affix: true },
    },
    {
        path: '/about',
        name: 'About',
        component: function () {
            return import('../views/About.vue')
        },
        meta: { title: 'About', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/index.vue'),
        meta: { title: '登录', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/401',
        name: '401',
        component: () => import('@/views/401'),
        meta: { title: '401', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/404'),
        meta: { title: '404', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/userManagement',
        name: 'userManagement',
        component: () => import('@/views/personnelManagement/userManagement'),
        meta: { title: '用户管理', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/roleManagement',
        name: 'roleManagement',
        component: () => import('@/views/personnelManagement/roleManagement'),
        meta: { title: '角色管理', icon: '', affix: true },
        hidden: true,
    },
    {
        path: '/menuManagement',
        name: 'menuManagement',
        component: () => import('@/views/personnelManagement/menuManagement'),
        meta: { title: '菜单管理', icon: '', affix: true },
        hidden: true,
    },]
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    // history: createWebHashHistory(),
    routes
})

export default router

 main.js 引入路由,修改浏览器页面title:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import 'babel-polyfill'
import "./mock.js"
import './router/index'

const app = createApp(App)
router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title;
    }
    next();
});
app.use(store)
app.use(router)
app.use(ElementPlus)
app.mount('#app')
原文地址:https://www.cnblogs.com/moguzi12345/p/14666611.html