解决动态添加路由,F5刷新问题

login.vue
<template>
  <div class="login-form-div">
    <el-row type="flex" justify="center">
      <el-col :span="20" class="login-div LoginByAccount">
        <div class="title">登录</div>
        <el-form :rules="loginInfoRules" ref="ruleForm" :model="loginInfo">
          <el-form-item prop="accountCode">
            <el-input
              v-model.trim="loginInfo.accountCode"
              type="text"
              placeholder="请输入手机号码/邮箱地址/用户名"
              prefix-icon="iconfont icon-icon-131"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              maxlength="20"
              minlength="8"
              v-model="loginInfo.password"
              type="password"
              placeholder="请输入登录密码"
              prefix-icon="iconfont icon-icon-24"
            ></el-input>
          </el-form-item>
            <el-form-item label-position="left" prop="verificationCode">
            <el-col :span="14">
              <el-input
                v-model.trim="loginInfo.verificationCode"
                type="text"
                placeholder="请输入短信验证码"
                prefix-icon="iconfont icon-icon-119"
                class="validate-code-input"
              ></el-input>
            </el-col>
            <el-col class="line" :span="1">&nbsp;</el-col>
            <el-col :span="9">
              <getCode/>
            </el-col>
          </el-form-item>
          <el-button class="log-in" @click="handleLogin('ruleForm')">登录</el-button>
        </el-form>
        <el-row type="flex" justify="space-around" class="commot">
          <el-col :span="12">
            <span class="sizeColor cursor" @click="forgetPassword">忘记密码?</span>
          </el-col>
          <el-col :span="12" class="sizeColor cursor size-align">
            <router-link :to="{'name':'register'}" tag="span">
              <span>注册账户</span>
            </router-link>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { validatePhoneUser, validatePassword } from "@/utils/validate"
import { staticRoutes, dynamicRoutes } from '@/router/index'
import code from "@/components/code/Code"
export default {
  // name: 'login',
  components: {
    getCode: code
  },
  data() {
    const identifyingCodeLegal = (rule, value, callback) => {
      if (value) {
        if (value.length === 4) {
          callback()
        } else {
          callback(new Error("请输入正确的短信验证码"))
        }
      } else {
        callback(new Error("请输入短信验证码"))
      }
    }
    // 用户账号规则校验
    const accountCodeLegal = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("请输入手机号码/邮箱地址/用户名"))
      } else {
        callback()
      }
    }
    // 手机号规则校验
    const accountCodePhone = (rule, value, callback) => {
      if (value) {
        if (!validatePhoneUser(value)) {
          callback(new Error("请输入正确的手机号"))
        } else {
          callback()
        }
      } else {
        callback(new Error("请输入手机号码"))
      }
    }
    // 密码规则验证
    const passwordLegal = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("请输入密码"))
      } else {
        callback()
      }
    }
    return {
      loginInfo: {
        accountCode: "",
        password: "",
        verificationCode: ''
      },
      loginInfoRules: {
        accountCode: [{ validator: accountCodeLegal, trigger: "blur" }],
        password: [{ validator: passwordLegal, trigger: "blur" }],
        verificationCode: [{ validator: identifyingCodeLegal, trigger: 'blur' }]
      }
    }
  },
  mounted() {
  },
  methods: {
    handleNodeClick(data) {
      console.log(data)
    },
    handleClick() {},
    hand() {
      window.open("http://www.baidu.com")
    },
    // 用户登录
    handleLogin(nameForm) {
      this.$refs[nameForm].validate(valid => {
        // 数据传递的规则验证
        if (valid) {
          let smt= dynamicRoutes;
          // console.log(smt)
          // let smts=smt.push({path:'*',redirect: '/404'})
          // this.$router.addRoutes(dynamicRoutes.concat([{path:'*',redirect: '/404'}]))
          sessionStorage.setItem("router", JSON.stringify(dynamicRoutes));
          this.$store.commit('SET_ID','');
          // this.$router.options.routes.push(dynamicRoutes)
          console.log(sessionStorage.getItem('router'))
          console.log(this.$router,'router');
          this.$router.push("/home1")
        } else {
          return false
        }
      })
    },
    forgetPassword() {
      this.$router.push("/forgetPassword")
    }
  }
}
</script>

<style lang="scss" scoped>
.login-form-div {
  width: 390px;
  margin: 0 auto;
  padding-top: 15px;
  -moz-box-shadow: 0px 0px 5px 5px #ddd; /* 老的 Firefox */
  box-shadow: 0px 0px 5px 5px #ddd;
  border-radius: 10px;
}
.title{
  color:#FF6600;
text-align: center;
font-size: 30px;
padding: 10px 0;
}
.commot {
  font-size: 14px;
  margin: 20px 0;
  text-align: left;
}
.pass {
  text-align: right;
  padding-bottom: 16px;
}
.sizeColor {
  color: #333;
  font-size: 14px;
}
.cursor {
  cursor: pointer;
}

.size-align {
  text-align: right;
}

.log-in {
  width: 100%;
  background: #FF6600;
  color:#fff;
  font-size:20px;
}

.weixin {
  font-size: 14px;
  color: #606266;
  padding-right: 24px;
  position: relative;
  color: #909399;
  .weixin-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 16px;
    height: 16px;
    background-image: url("./image/weChat.svg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}
.medium-button {
  width: 100%;
}

.forget-password-div {
  width: 325px;
  margin: 0 auto;
}
</style>
index.vue
// import Vue from 'vue'
// import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import LoginLayout from '@/views/layout/LoginLayout'
import MainLayout from '@/views/layout/MainLayout'
import HeaderLayout from '@/views/layout/headerlayout'
// Vue.use(Router)

// export default new Router({
//   routes: [
//     {
//       path: '/',
//       name: 'HelloWorld',
//       component: HelloWorld
//     },
//     {
//       path: '/401',
//       component: () => import('@/views/error/401')
//     },
//     {
//       path: '/404',
//       component: () => import('@/views/error/404')
//     },
//     {
//       path: '*',
//       redirect: '/404'
//     }
//   ]
// })
export const staticRoutes = [
  // {
  //   path: '/HelloWorld',
  //   name: 'HelloWorld',
  //   component: HelloWorld
  // },
  {
    path: '/401',
    component: () => import('@/views/error/401')
  },
  {
    path: '/404',
    component: () => import('@/views/error/404')
  },
  // {
  //   path: '*',
  //   redirect: '/404'
  // },
  {
    path: '',
    component: LoginLayout,
    redirect: '/login',
    children: [
      {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/Login')
      }
    ]
  },
  {
    path: '/forgetPassword',
    component: LoginLayout,
    children: [
      {
        path: '',
        name: 'forgetPassword',
        component: () => import('@/views/forgetpassword/ForgetPassword')
      }
    ]
  },
  {
    path: '/register',
    component: LoginLayout,
    children: [
      {
        path: '',
        name: 'register',
        component: () => import('@/views/register/Register')
      }
    ]
  },
  {
    path: '/socialWorker',
    name: 'socialWorker',
    component: () => import('@/views/socialWorker/socialWorker')
  },
  {
    path: '/institutions',
    name: 'institutions',
    component: () => import('@/views/institutions/institutions')
  }
]
export const dynamicRoutes = [
  {
    path: '/header',
    component: HeaderLayout,
    // redirect: '/myProject',
    children: [
      {
        path: '/myProject1',
        component: MainLayout,
        meta: {
          title: '继续教育',
          icon: 'icon-ic_dashboard',
          disabled: false
        },
        children: [
          {
            path: '/home1',
            name: 'home1',
            title: '继续教育',
            component: () => import('@/views/home/home')
          }
        ]
      },
      {
        path: '/myProject',
        component: MainLayout,
        meta: {
          title: '个人中心',
          icon: 'icon-ic_dashboard',
          disabled: false
        },
        children: [
          {
            path: '/home2',
            name: 'home2',
            component: () => import('@/views/home/home')
          }
        ]
      }
    ]
  },
  {
    path: '/list',
    component: () => import('@/views/login/list')
  },
   {
    path: '*',
    redirect: '/404'
  }
]
pression.js
// 路由拦截
// import router from './index'
import { staticRoutes, dynamicRoutes } from './index'
import store from '../store'
import {
  getToken
} from '@/utils/auth' // 验权
import 'nprogress/nprogress.css' // 进度条
import NProgress from 'nprogress' // 进度调样式
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let router = new Router({ routes: staticRoutes })
NProgress.configure({
  showSpinner: false
})
router.beforeEach((to, from, next) => {
  NProgress.start()
  // console.log(to,'to',from,'form',next,'next')
  // if(to.name){
  //   store.commit('CHANGE_PATH', to.name);
  // }
  // console.log(store.state.user.id, 'id')
  if(sessionStorage.getItem('router')){
    if (to.path === '/login') {
      next()
    } else {
      // next()
        if (!store.state.user.id) {
          // let routes= JSON.parse(sessionStorage.getItem('router'));
          store.dispatch('Change', 'qwe')
          router.addRoutes(dynamicRoutes)
          // console.log(router)
          console.log(2)
          // next()
          next({ ...to, replace: true })
        } else {
          console.log(5)
          console.log(getToken(), router)
          next()
        }
      // }
     
    }
  } else {
    next()
    // router.push({path:'/login'})
    NProgress.done()

  }
 
  // if (to.matched.some(res => res.meta.requireAuth)) { // 判断是否需要登录权限
  //   if (getToken()) { // 判断token是否存在
  //     next()
  //   } else {
  //     router.push({
  //       path: '/login'
  //     })
  //   }
  // } else if (to.path === '/login') {
  //   next()
  // } else {
  //   next()
  //   NProgress.done()
  // }
})

router.afterEach(() => {
  NProgress.done()
})

export default router

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值