前言:
使用vue的时候总会使用到前端vue-router路由,检验登陆状态,检验是否路由跳转,就需要路由守卫来解决, 这一篇将会多多少少能够让你运用路由守卫。
一、全局路由守卫
首先,
在vue文件目录里找到 main.js 文件
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
router.beforeEach((to, from, next) => {
// ...
});
new Vue({
el: "#app",
store,
router,
components: { App },
template: "<App/>"
});
这是全局的路由守卫,每次在路由跳转的时候,都会触发这个函数。
其中,
to 就是去的路由 去往哪儿
from 是跳转前的路由 从哪儿跳过来的
next 就是确认跳转 ok
router.beforeEach((to, from, next) => {
//vuex里面的userinfo是否已经存在,不然就直接跳转到登录页面
if(store.state.userInfo || to.path === "/login") {
next();
} else {
next({
path: "/login"
})
}
});
这个 全局的 路由守卫,可以用来检验网址用户是否已经登陆,
因为每次跳转的时候,都会执行这个函数,
只要我们在这个函数里面,设置就ok了。
二、路由独享的守卫
路由独享的守卫:
是指某个路由页面独享这个守卫,其他的路由不能使用,提高了路由守卫的灵活性。
如下:
routes: [
{
path: "/home",
component: home,
beforeEnter: (to, from, next) => {
//进入这个路由前,检验登陆
if(store.state.userInfo || to.path === "/login") {
next();
} else {
next({
path: "/login"
})
}
}
}
];
三、组件内的路由守卫
组件内的路由守卫:
判断用户要离开该路由的时候,检验是否用户已经保存该编辑页面内容,
如果没有,跳出提示框,是否不保存离开该页面。
<template>
<h1> Tenderness 新宇</h1>
</template>
<script>
export default {
data(){
return{
name:" Tenderness 新宇"
}
},
//路由进入前调用
beforeRouteEnter:(to, from, next)=>{
alert("你好呀"+this.name);
alert(to.path + from.path);
next();
next(vm => {
alert("你好呀"+vm.name);
})
},
//路由离开时调用,可以用在编辑页面
beforeRouteLeave:(to, from, next) => {
if(confirm("离开该页面,不会保存你的操作,确认离开吗?") == true){
next();
}else{
next(false);
}
}
}
</script>
四、怎么使用呢?
在项目中安装 vue-router
npm安装 npm install vue-router
淘宝镜像安装 cnpm install vue-router
切换镜像源 这里需要全局下载nrm
然后 nrm ls 可以查看到我们在哪一个中
然后 nrm use 想要用到的安装方式 eg: nrm use cnpm
这时候就已经切换到淘宝镜像了在项目中引入vue-router
import router from './router'
- 登陆路由拦截
router.beforeEach((to, from, next) => {
if (to.name !== 'login') {
if (!window.sessionStorage.tokenId) {
router.push({name: 'login'})
}
}
next()
})
五、路由传参
VUE 路由父子传参的方式
方法一:
getDescribe(id) {
// 直接调用router.push实现携带参数的跳转this,
this.router.push({
path:'/describle/${id}' //路由地址
})
需要在path中添加 /:id 来对应 $router.push 中 path 携带的参数。
在子组件中可以使用来获取传递的参数值
{
path: '/describe/:id',
name: '组件名',
component: 组件名
}
子组件中: 这样来获取参数 this.$route.params.id
方法二:
this.$router.push({
name:'组件名',
params:{
id:id
}
})
注意这里不能使用 :/id 来传递参数了,
因为父组件中,已经使用params来携带参数了。
{
path: '/describe',
name: '组件名',
component: 组件名
}
子组件中: 这样来获取参数 this.$route.params.id
好啦 就到这里吧 希望看到的你 有所帮助

版权声明:本文为tendernessxy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。