今天在做管理系统的时候,做了路由验证,未登录的跳转到登录页,但是登录页刷新的时候后台的导航页面出现了,这显然是不可以的,原因是因为在app.vue放了组件,导致刷新的一瞬间这些组件就出现了,解决办法就是判断用户是否登陆,如果未登录就直接显示登陆界面,其余组件不要出现
<template> <div id="app"> //根据username判断用户是否登陆 <div v-if="username"> <homes></homes> </div> <div v-else> <router-view></router-view> </div> </div> </template> <style> html, body { width: 100%; height: 100%; } </style> <script> import homes from "./views/index"; import { mapActions, mapState } from "vuex"; import cookies from "js-cookie"; export default { data() { return {}; }, computed: { ...mapState("users", ["username", "userid"]) }, created() { var self = this; if (!this.username) { this.usernames = cookies.get("USER_NAME"); this.userids = cookies.get("USER_ID"); if (this.usernames || this.userids) { this.setUser({ username: self.usernames, userid: self.userids }); } } else { this.$router.push("/login"); } }, mounted() { console.log(this.username); }, methods: { ...mapActions("users", ["setUser"]) }, components: { homes } }; </script>
还有一个问题就是element循环路由的时候一直报错,如果你需要使用element循环路由,麻烦再二级路由的时候把一级的也带上
import Vue from 'vue' import Router from 'vue-router' import Cookies from 'js-cookie' Vue.use(Router) const router = new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', redirect: '/index', show: false }, { path: '/index', name: 'home', component: () => import('./views/index.vue'), meta: { auth: true, title: '首页', icon: "el-icon-s-home" } }, { path: '/category', name: 'category', component: () => import('./views/category/category.vue'), meta: { auth: true, title: '栏目管理', icon: "el-icon-menu" }, children: [ { path: '/category/addCategory', name: 'addCategorys', component: () => import('./views/category/category.vue'), meta: { auth: true, title: '添加栏目' } } ] }, { path: '/login', name: 'login', show: false, component: () => import('./views/login.vue'), meta: { title: '登陆' } }, ] }) router.beforeEach((to, from, next) => { console.log(to) if (to.matched[0].meta.auth) { if (Cookies.get('USER_ID')) { next() } else { next({ path: '/login' }) Vue.prototype.$message.warning('检测到您还未登录,请登录后操作!') return false; } } else { if (Cookies.get('USER_ID')) { if (to.path == '/login') { next({ path: '/' }) } } next() } }) export default router
原因是因为二级路由循环后,赋值给index,只是当前的二级路由,并没有携带一级路由,或者在循环的时候拼接二级路由
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接