Vue3.X项目的路由配置

本文介绍如何在Vue3项目中配置vue-router4.x版本,包括安装、基本路由设置、路由重定向及嵌套路由定义等关键步骤。

注意:在vue3.x项目中,只能安装vue-router4.x版本

1.安装命令

npm i vue-router@next -S

2.在项目中新建router.js路由模块 

//导入路由模块
import { createRouter, createWebHashHistory } from 'vue-router'

import MyHome from '@/components/MyHome.vue'

// 创建路由实例对象
const router = createRouter({
  //createWebHashHistory声明路由模式(hash模式)
  history: createWebHashHistory(),
  routes: [
    //path要匹配的hash地址,component匹配地址要显示的组件
    { path: '/home', component: MyHome }
  ]
})

// 共享路由模块
export default router

3.在main.js文件中挂载路由模块

import { createApp } from 'vue'
import router from '@/components/router'

import App from './App.vue'

const app = createApp(App)
//挂载路由模块
app.use(router)

app.mount('#app')

4.在组件中使用路由

<template>
  <h1>app根组件</h1>
  <router-link to="/home">首页</router-link>
  <hr />
  <router-view></router-view>
</template>

<script>

export default {
  name: 'App',
}
</script>

<style>
</style>

 路由重定向

//导入路由模块
import { createRouter, createWebHashHistory } from 'vue-router'

import MyHome from '@/components/MyHome.vue'
import MyFruit from '@/components/MyFruit.vue'
import MyWine from '@/components/MyWine.vue'

// 创建路由实例对象
const router = createRouter({
  //createWebHashHistory声明路由模式(hash模式)
  history: createWebHashHistory(),
  //自定义路由高亮的class类,默认的router-link-active类名会被覆盖
  linkActiveClass: 'my-router-active',
  routes: [
    //重定向路由
    { path: '/', redirect: '/home' },
    //path要匹配的hash地址,component匹配地址要显示的组件
    { path: '/home', component: MyHome },
    {path: '/fruit',component: MyFruit},
    { path: '/wine', component: MyWine }
  ]
})

// 共享路由模块
export default router

嵌套路由定义和重定向

使用children属性声明子路由

{
     path: '/fruit',
     component: MyFruit,
     //子路由重定向
     redirect: '/fruit/apple',
     children: [
        { path: 'apple', component: MyApple },
        { path: 'orange', component: MyOrange }
     ]
 },
<template>
  <div class="">
    <h3>水果</h3>
    <router-link to="/fruit/apple">苹果</router-link>
    <router-link to="/fruit/orange">橘子</router-link>
    <hr />
    <router-view class="fruit-router"></router-view>
  </div>
</template>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值