vue3中vue-router的使用

首先需要使用vue-router在vue2和vue3的用法也是存在差别的

  1. 首先你需要安装vue-router
npm install vue-router@next -S
  1. 然后再项目的根目录下面src文件夹下面新建router这个文件夹, router中新建index.js这个文件
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    // 路由懒加载
    component: () => import('../views/home.vue'),
    meta: {
      name: 'why',
      age: 20,
      height: 1.88
    },
    children: [
      {
        path: 'message',
        component: () => import('../components/message.vue')
      },
      {
        path: 'production',
        component: () => import('../components/production.vue')
      }
    ]
  },
  {
    path: '/about',
    component: () => import('../views/about.vue')
  },
  {
    path: '/user/:username/id/:id',
    component: () => import('../views/User.vue'),
    name: 'username',
    meta: {
      name: 'username'
    }
  },
  {
    path: '/login',
    component: () => import('../components/Login.vue')
  },
  {
    path: '/:pathMatch(.*)',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory(),
  linkActiveClass: 'why-active',
  linkExactActiveClass: 'why-exact-active'
})
// 动态添加路由
const Category = {
  path: '/category',
  component: () => import('../components/Category.vue')
}
// 动态添加顶级路由
router.addRoute(Category)
// 动态添加二级路由
const moment = {
  path: 'moment',
  component: () => import('../components/moment.vue')
}
router.addRoute('home', moment)

let count = 0
//  to: 表示跳转的路由对象, from表示从哪里跳过来的
router.beforeEach((to, from) => {
  console.warn(to, from)
  // eslint-disable-next-line no-template-curly-in-string
  console.log(`路由跳转${++count}`)
  // if (to.path.indexOf('home') !== -1) {
  //   return '/login'
  // }
  if (to.path !== 'login') {
    // return '/login'
    const token = window.localStorage.getItem('key')
    if (!token) return '/login'
  }
  // return false
})
export default router

在入口文件main.js中给与配置信息

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)

app.mount('#app')

以上就是vue-router在vue3中的使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值