用于实现vue项目中各个组件之间的切换,在单页面应用中实现页面切换的效果。
Vue history 和 hash 两种模式的优缺点 - 知乎 (zhihu.com)
在Vue项目中创建路由功能,有几种不同的方式:
npm install vue-router
在router目录下的index.js文件中实现相应的路由配置,可配置路径、名称、对应vue组件。
相对路径和绝对路径的区别:相对路径(不带‘/’)会拼接父级路由,绝对路径(带‘/’)是配置的完整路由
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component:HomeView
}
]
})
// 嵌套路由
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'index',
component: IndexView,
children:[
{
path: 'student',
name: 'student',
component: StudentShow
}
]
}
]
})
vue3有两种路由,分别是Hash路由和history路由。
路由的hash和history模式的区别
hash
模式url带#号,history
不带#号hash
模式前端路由修改的是hash值
(#及以后),对后端没影响,因此改变hash
也不会重新加载页面,比如修改为了不存在的#123页面,页面不会跳转;history
模型刚好相反,没有对应的页面就会出现404示例说明:
<header>
<nav>
<RouterLink to="/home">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</header>
<RouterView></RouterView>