提示:专栏内容均为原创,搬运必究
文章目录
一、路由的两种模式?
1.hash模式
-
- hash模式下地址栏中
带#
,切换路由,变化的是#后面的内容;
- hash模式下地址栏中
-
- hash模式下路由改变后
手动刷新页面不会报错
;
- hash模式下路由改变后
-
- 因为hash模式请求页面的地址永远是# 前面的内容,所以总是能请求成功,得到index.html页面,再
通过路由渲染
显示对应得组件;
- 因为hash模式请求页面的地址永远是# 前面的内容,所以总是能请求成功,得到index.html页面,再
-
- hash模式下url变化是通过浏览器的
hashchange
方法监听;
- hash模式下url变化是通过浏览器的
-
- hash 能兼容到
IE8
.
- hash 能兼容到
2.history模式
-
- history模式下地址栏中
没有#
,从视觉上更加美观;
- history模式下地址栏中
-
- history 只能兼容到
IE10
;
- history 只能兼容到
-
- 利用H5的 history中新增的两个API
pushState()
和replaceState()
和一个事件onpopstate
监听URL变化;
- 利用H5的 history中新增的两个API
-
- history 模式需要后端配合将所有访问都
指向 index.html
,否则用户刷新页面,会导致 404 错误
- history 模式需要后端配合将所有访问都
二、使用
1. 先看实战一创建的项目,生成的路由文件
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
}
]
})
export default router
上方是两种基础的路由写法
/
就是站点进来展示的页面(首页),上方先导入Home这个组件,再对应component
/about
则使用了路由懒加载的方式(延迟加载,即在需要的时候进行加载,随用随载。)
- 在script中通过
router.push('/')
和router.push('/about')
可以千万相应的页面
2.带参数的动态路由
代码如下(示例):
{
path: '/product/:id',
component: HomeView
}
- 当你的地址为
/product/xxxx
的时候,页面展示的内容也是HomeView这个组件内的内容; - 当你进入了
/product/xxxx
页面,在script代码中,可以通过this.$route.params
获取到:id
的值; - 在template,通过
{{ $route.params.id }}
,显示:id
的值。
3. 嵌套路由
代码如下(示例):
{
path: '/product/:id', //动态路由
component: HomeView,
children: [
{
path: 'detail', //嵌套路由
component: HomeView,
},
],
}
简单来说,使用嵌套路由就可以实现类似
localhost:3000/product/001/detail
的地址,001则对应动态的product id,detail则为产品的详情页,这样就可以实现根据动态id前往
该id的详情页地址,再配合api就可以动态加载不同产品的详情页面`
4. 路由重定向
代码如下(示例):
{
path: '/test',
redirect: '/home'
}
当我们在地址栏输入
/test
前往该页面的时候,会重定向前往/home
页面
三、不同方式导航到不同的位置
1.声明式导航
代码如下(示例):
<router-link :to="...">
2.编程式导航
代码如下(示例):
// 字符串路径
router.push('/users/eduardo')
// 带有路径的对象
router.push({ path: '/users/eduardo' })
// 命名的路由,并加上参数,让路由建立 url
router.push({ name: 'user', params: { username: 'eduardo' } })
// 带查询参数,结果是 /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } })
// 带 hash,结果是 /about#team
router.push({ path: '/about', hash: '#team' })
总结
本篇文章讲述了路由的模式和使用的方法,路由这块有很多需要知道的东西
- 下一篇文章将讲解Router的一些进阶方法