// 安装
npm install vue-router@4
// 创建 router 文件夹 index 文件
// 3.0 以上的版本引入 createRouter
import { createRouter } from 'vue-router'
const router = createrouter({})
// 创建完后需要到 main 主文件注册申明
import router from './router'
createApp(App).use(router).mount('#app')
// 最后在页面主文件 App.vue 中使用 router-view 当容器使用
// router-view: 路由出口,路由匹配到的组件渲染在里面
createRouter 对象里包含多个参数,最主要的就是 routes 设定路由,其它参数可查看文档
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes:Array<RouteRecorRaw> = [
{
path: '/',
// 使用 import 函数方式的导入可以使项目在打包时帮助分割做性能优化
component: ()=> import('../components/login.vue')
},
{
path: '/reg',
component: ()=> import('../components/reg.vue')
},
]
const router = createrouter({
history: createWebHistory(),
routes: routes
})
export default router
Mode 配置
vueRouter2 中 mode 配置一般就是 hash / history / abstact (ssr)
history 实现
没有 #号, 通过H5 中的 history 提供了 pushState 和 replaceState 改变地址,还提供了 popState 事件实现监听, windows.addEventListener( popState )
// pushState / replaceState 不会引起页面刷新
// 前进后退改变URL 会触发 popState
// pushState / replaceState 或 a标签 不会触发 popState
// 通过 history 的 back、go、forward 方法可以触发 popState
跳转方式
router-link path跳转、name对象跳转、a标签herf跳转、 编程式跳转
页面刷新
router-link不会触发页面刷新
a 标签会刷新
历史记录
router-link 通过给标签添加 replace 属性实现不保留历史记录
JS 编程式导航跳转的时候使用 router.replace() 即可