什么是路由
路由这个概念实际是创建地址与对应页面(组件)映射关系
url两种模式
hash
hash路由url会多出#,本质是直接赋值window.localtion.hash来改变url,页面不会发生刷新
history
history是html5新增的,它的六种模式改变url页面不会刷新
使用路由
- 安装
npm install vue-router
- 配置路由文件 (src/router/index.js)
import { createRouter, createWebHashHistory } from 'vue-router'
import HelloWorld from '@/components/HelloWorld.vue'
const router = createRouter({
history: createWebHashHistory(),
routes:[
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: HelloWorld
},
{
path: '/:pathMatch(.*)',
component: () => import('../components/404.vue')
}
]
})
console.log(window.location)
router.beforeEach((to,form)=>{
console.log(to);
// return
})
export default router
使用 < router-view /> 显示url匹配路径
name与元信息meta
name属性必须配置独一无二
meta元信息可以用设置我们需要一些条件
配置404页面
路由嵌套
编程式路由
编程式路由push、replace、go、back、forward
replace相当于替换当前位置,url栈不会存上一步地址
router.push({ path: '/home', replace: true })
router.push('/home')
// 相当于
router.replace({ path: '/home' })
// 向前移动一条记录,与 router.forward() 相同
router.go(1)
// 返回一条记录,与 router.back() 相同
router.go(-1)
// 前进 3 条记录
router.go(3)
// 如果没有那么多记录,静默失败
router.go(-100)
// 回退一步
router.back()
// 向前一步
router.forward()
query参数
router-link
router-link相当于a链接作用
路由懒加载
当应用越来越大时,则需要使用路由懒加载,使不同的路由对应的组件分割成不同的模块(打包成js文件),当路由访问才加载对应组件,这样才高效。也可以提高首屏渲染时间
动态路由
- 添加路由
router.hasRoute():检查路由是否存在。router.getRoutes():获取一个包含所有路由记录的数组。