Vue实现登录保存token并校验实现保存登录状态

淩亂°似流年 2024-04-06 15:28 183阅读 0赞

文章目录

  • 一、登录vue
  • 二、路由index

一、登录vue

  1. <script>
  2. import request from "@/axios/baseURL";
  3. import router from "@/router";
  4. // 接口数据初始化
  5. const FORM_DATA = {
  6. userName: "",
  7. password: "",
  8. };
  9. export default {
  10. data() {
  11. return {
  12. FORM_DATA,
  13. };
  14. },
  15. created() {
  16. console.log("登录界面");
  17. },
  18. methods: {
  19. login() {
  20. request.post("/systemUser/login", this.FORM_DATA).then((res) => {
  21. var code = res.data.code;
  22. var message = res.data.message;
  23. this.$message(message);
  24. if (code == 0) {
  25. localStorage.setItem("token", res.data.data.token);
  26. router.push("/library");
  27. }
  28. console.log(res);
  29. });
  30. },
  31. },
  32. };
  33. </script>

二、路由index

  1. // 导航守卫
  2. router.beforeEach((to, from, next) => {
  3. const token = localStorage.getItem('token');
  4. const outerPaths = ['/homePage']; // 当前 path 不需要登录也可以进入系统,但是只能操作当前页面
  5. if (!token && !outerPaths.includes(to.path)) {
  6. next('/homePage');
  7. } else {
  8. // if (to.path == "/auth") {
  9. // document.title = to.meta.title // 进入这个页面会被更改页面标题
  10. // } else document.title = 'CPS流量变现后台管理系统'
  11. next();
  12. }
  13. });

在这里插入图片描述

  • 坚持不懈,努力奋斗,心之所向必定成真。
  • 拥有激情与决心,创造无限可能的未来。
  • 放飞心灵,勇往直前,追逐梦想的星辰大海。
  • 不怕失败,享受过程,每一次尝试都是一种进步。
  • 集中注意力,努力前行,不要停下,直到成功只是习惯。

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读