一、vue-router 导入项目
npm init vue@latest创建的项目是有 vue-router 可选项自动导入
npm init vite@latest创建的项目需要手动导入
1.创建 vue-router 实例
import { createRouter,createWebHashHistory } from 'vue-router'
const router = createRouter({
//createWebHashHistory hash 模式 ; createWebHistory histiry 模式
history: VueRouter.createWebHashHistory(),
routes:[
{
path: '/',
name: index,
component: ()=>import('../view/index.vue'),
children: [
//子路由
]
}
]
})
2. 将 vue-router 实例导入 main.ts , 并通过user 挂载在 app 实例上
import routes from "./router";
createApp(App)
.use(routes)
.mount('#app')
3.使用 router-view 渲染路由
二、vue-router 跳转的几种方式
1.router-link 跳转
<router-link to="/path"></router-link>
2.通过事件触发跳转, 并传递参数
<button @click="toPath('/path')">path跳转</button>
<button @click="toName('name')">name跳转</button>
//script
//导入 useRouter 并创建 router 实例
import { useRouter } from 'vue-router'
const router = useRouter()
const to = (path)=>{
router.push({
path,
query: {} //传参 会通过url传递参数
})
}
const toName = (name)=>{
router.push({
name,
params: id // 用于动态路由的id (/path/:id)
//使用params传递非动态路由参数 会出现 warn 警告 Discarded invalid param(s) "id" when navigating
// https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22
// 所以不建议params 传递 反模式路由参数 原因有很多 ,其一就是重新加载页面会丢失参数
// 幸运的是 这种反模式有多种替代方法:
// 将数据放在像pinia这样的存储中:如果数据跨多个页面使用,这是相关的
// 通过在路由的 path 上定义数据或将其作为 query 参数传递,将数据移动到实际参数
// 将数据作为 state 传递,以将其保存到历史记录 API 状态
// 在导航防护期间将其作为新属性传递给 to.meta .这称为瞬态,由于它位于导航防护中,因此在重新加载页面时将保留它
})
}
3.通过 go(1) , back() 跳转上一页,下一页。
//script
go(1) // 去往历史记录 上一页
go(-1) //去往历史记录 下一页
back() // 同go(-1)
4.使用 location.replace('/') 进行跳转,页面会进行刷新
//script
location.replace('/') //跳转到根目录
5.使用 a 链接进行跳转 , 页面会进行刷新
<a herf="/"></a> //跳转到根目录
6.使用路由重定向 redircet
routes:[
path: '/',
redircet: '/index' //访问跟路由 会自动跳转到 /index路由
]
三、vue-router 接收传递过来的参数
import { useRoute } from 'vue-router'
coant route = useRoute() //route 用于接收传递过来的参数
const data = route.query //使用 path query 传递过来的参数
const data2 = route.params // 使用 name params 传递过来的 路由动态参数(/name/:id)
四、嵌套路由
routes: [
{
path: '/index',
name: index,
component: ()=>import('../view/index.vue'),
children: [
//子路由
{
path: '/page1'
...
},
{
path: '/page2'
...
},
]
}
]
//使用到嵌套路由时候 需要在path 中加入父级path
<router-link to='index/page1'><router-link>
<router-link to='index/page2'><router-link>
// 使用 <RouterView></RouterView> 渲染种子路由