路由就是通过互联的网络把信息从源地址传输到目的地址的活动。
什么是前端渲染?什么是后端渲染?
1.后端路由阶段:后端处理URL和页面之间的映射关系
2.前后端分离阶段:后端只负责数据,不负责任何阶段的内容
3.单页面复用(SPA页面)阶段:整个网站只有一个HTML页面。
前端路由:管理URL和页面的映射关系
hash和history
//改变URL,页面不刷新
location.hash = 'home'
//h5新增history
history.pushState({},'','home')//类似于栈结构,pushSate相当于入栈,可以返回
history.replaceState({},'','home')//替换,不能反回
history.go(-1) //等同于 history.back()
history.go(2) //传入数字,跳到任意栈
将默认的hash模式改成history模式
//main.js中
new Vue({
el: '#app',
router,
mode:;history
components: { App },
template: '<App/>'
})
rouer-link
router-link标签,默认渲染成a标签
//使用tag属性,渲染成button标签
<router-link tag='button'></router-link>
//使用replace方法,不能返回
<router-link tag='button' replace></router-link>
//选中的class名改成active
<router-link tag='button' active-class='active'></router-link>
//统一改 路由添加属性 linkActiveClass:'active'
通过代码跳转路由
this.$router.push('/home') //可以返回
this.$router.replace('/home') //不可以返回
动态路由的使用
//路由配置页面
{
path:'/user/:userId',
component:User
}
//跳转路由界面
<router-link :to="'/home/'+userId"></router-link>
//或者
this.$router.push('/home/'+this.userId)
//拿到userId
computed:{
userId() {
return this.$route.params.userId
}
}
//或者
{{$route.params.userId}}
区分 $router和 $route
$router是router文件夹暴露出来的大的路由对象
$route是当前正在活跃的路由
路由懒加载
{
path:'/home',
component: () => import('../components/Home)
}
路由嵌套
{
path:'/home',
component: () => import('../components/Home),
children:[
{
path:'news',
component: () => import('*****')
},
//设置默认路径
{
path: '/',
redirect: 'news'
}
]
}
//跳转
<router-link :to='/home/news'></router-link>
传递参数的方式
//传输
<router-link :to="{path:'/profile',query:{age:18,height:1.88}}"></router-link>
this.$router.push({
path:'/profile',
query:{age:18,height:1.88}
})
//取出
$route.query.age
$route.query.height
导航守卫:监听路由跳转
//前置钩子(guard),在路由跳转之前的回调
router.beforeEach((to, from, next) => {
next() //这里必须调next函数,否则路由不会跳转
//从from跳到to
document.title = to.matched[0].meta.title //参数to,代表跳转过去的路由对象。mate:元数据(描述数据的数据)
})
//后置钩子(hook),路由调转后的回调
router.afterEach((to, from) => {
//执行代码块
})
//路由独享守卫
routes: [
{
path: 'foo',
component: Foo,
beforeEnter: (to, from, next) =>{
// ...
}
}
]
3万+

被折叠的 条评论
为什么被折叠?



