1.1路由守卫:
1.(路由守卫用来监控登录页面,如果未登录就不让跳转列表)
导航守卫:提供的导航守卫主要用来通过跳转或取消的方式守卫导航
1.全局守卫:管路由匹配哪一个地址,都会触发
2.路由独享守卫 beforeEnter
3.组件独享守卫 beforeRouteEnter、beforeRouteUpdate、beforeLeave
2.三个参数:
to:将要跳转的路由对象(参数)我是谁
from:从哪个路由来的(存储的也是路由对象)我从哪里来
next:向下执行,不执行,不继续,我要干什么
3.分为前置和后置守卫:
前置守卫:beforeEach 路由跳转前的生命周期
后置守卫:afterEach 路由跳转后的生命周期
4.组件内的守卫:
进入组件之前的生命周期:beforeRouterEnter
路由发生变化的生命周期:beforeRouterUpdate
路由立开的生命周期:beforeRouterLeave
5.按需加载路由:
vue的路由中router下的index.js:可以写按需加载路由
例子:[{path:'/home',name:'home',component:()=>import('../hezi/home.vue')}]
优点:不占用内存,提高性能,提高用户体验度。
1.2.全局守卫:前置守卫例子
前置守卫:是跳转之前路由的守卫
必须用一个变量接收它。例子:
const routes=[
{path:'/',name:'hello',component:hello},
{path:'/home',name:'home',component:()=>import('../hezi/home.vue')}
]
const router=new VueRouter({//写入全局守卫接收
routes
})
router.beforeEach((to, from, next) => {
console.log('to',to);
console.log('from',from)
next();执行下一步
to:到哪里去
from:从哪里来
next:执行下一步,如果没有next执行,就不会执行下一步
})
1.3全局:前置守卫可以做判断登录,如果没有登录就不让跳转到这个页面
router.beforeEach((to, from, next) => {//前置守卫用方法里面写箭头函数(()=>{})
//假设的例子
let token=0;
if(to.path==='/home'){
if(token){
alert('登录了');
next();//跳到你定义的页面
}else{
alert('请登录页面');
next('/login');//跳到登录页面
}
}else{
next();//其它的就正常跳转
}
})
1.4. 全局守卫:后置守卫的例子
后置守卫:跳转之后路由的守卫
router.afterEach((to, from) => {//后置守卫只有两个参数to、from、
console.log('全局后置守卫')
console.log('to',to);
console.log('from',from)
to:到哪里去
from:从哪里来
})
1.5路由独享守卫:例子
独享守卫可以用来场景(有些页面需要,有些页面不需要)可以单独给某个页面加入独享守卫
const routes=[
{path:'/',name:'hello',component:hello,
beforeEnter:(to,from,next)=>{//路由独享用函数来写()=>{};
//三个参数意思如前置守卫上面一样
console.log('我是路由独享守卫');
next();
}},
{path:'/home',name:'home',component:()=>import('../hezi/home.vue')}
]
1.6组件独享守卫:例子
组件独享守卫是在组件内进行操作的和生命周期一样的使用方法
export default{
beforeRouteEnter(to,from,next){
console.log('进入组件之前的生命周期');
next();
},
//例子假设:场景路由的参数发生变化了,就可以重新调用接口
beforeRouteUpdate(to,from,next){//路由上发生的变化才会触发(例如传参)
console.log('组件发生变化的生命周期');
next();
},
beforeRouteLeave(to,from,next){
console.log('路由离开的生命周期');
next();
}
}
1.7路由的两种传参方式:params、query、
params:只能用name(内部的name名)引入路由传参
query:会出现在url上所有可以用path传参
每个组件都拥有路由提供的$route、$router、
$route:提供的是属性 params参数
$router:提供的是方法push、 go、back...
this.$router.push({name:'hello'})等...
1.使用params传参参数不会出现在url上,query会出现url上(接口的参数上面?后面(例子:/#/hello?m=100));
2.刷新页面时params参数会消失,而query不会消失
3.获取路由的方式:params=this.$route.params;或query=this.$route.query;
:router是方法route是属性:
params和query传参例子:
toa(){
this.$router.push({
path:'a',
query:{
m:100;
}
})
},
tob(){
this.$router.push({
name:'b',
params:{
n:200;
}
})
},
//mounted(){可以拿到被操作后的值(例子:this.$route;)}