注意:在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>

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

被折叠的 条评论
为什么被折叠?



