vue登录页

时间:2021-6-4 作者:qvyue

vue项目实现用户登录 以及携带token

调取登录接口 (首先明确一下要做到事情)
在前后端完全分离的情况下,Vue项目中实现token验证大致思路如下:

1.第一次登录的时候,前端调后端的登陆接口,发送用户名和密码
2.后端收到请求,验证用户名和密码,验证成功,就给前端返回一个token
3.前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面
4.前端每次跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面
5.每次调后端接口,都要在请求头中加token
6.后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401
7.如果前端拿到状态码为401,就清除token信息并跳转到登录页面
8.调取登录接口成功,会在回调函数中将token存储到localStorage和vuex中

vue登录页
image.png
一、前期准备

页面模板

登录

姓名:
密码:
export default { data() { return { username: "", password: "", }; }, methods: { handleLogin() { // 可以直接调用 fetchLogin ? // token this.$store .dispatch("login", { username: this.username, password: this.password, }) .then(() => { this.$router.push({ name: "photo", }); }); }, }, }; .loginContainer { margin: 0 auto; width: 600px; text-align: center; padding-top: 20px; padding-bottom: 50px; border: 1px solid; } .loginContainer input { margin-bottom: 20px; } .loginStyle { width: 160px; height: 40px; background: rgb(50, 203, 77); color: white; font-size: 17px; } .inputStyle { width: 200px; height: 30px; padding: 5px; outline: none; } .inputStyle:focus { border: 1px solid rgb(50, 203, 77); } form { position: relative; } .exchange { position: absolute; top: 8px; right: 65px; color: red; }

逻辑实现

export default {  
    data() { 
        return {
          loginForm: { 
               username: "",
               password: "",
          },    
        };  
     },  
    methods: { 
       ...mapMutations(["changeLogin"]),
       login() {
          let _this = this;

          /////判读账号密码是否输入,没有则alert 出来
          if (this.loginForm.username === "" || this.loginForm.password === "") {
            alert("账号或密码不能为空");      
          } else { 
             this.axios({          
                method: "post",
                url: "/user/login",
                data: _this.loginForm,
              })
                .then((res) => {
                    console.log(res.data);
                    _this.userToken = "Bearer " + res.data.data.body.token;

                    // 将用户token保存到vuex中 
                   _this.changeLogin({   
                       Authorization: _this.userToken,
                    });          
                   _this.$router.push("/home");
                    alert("登陆成功");     
                 })        
                 .catch((error) => { 
                   alert("账号或密码错误");   
                   console.log(error);
                  });
               }    
            },  
          },
};

vue登录页
image.png

2.在store文件夹下的index.js 添加 token

import Vuex from "vuex";
import Vue from "vue";
import { fetchLogin, fetchPhotos } from "../api";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: localStorage.getItem("token") || "",
    photos: [],
    pageSize: 5,
    pageTotal: 10,
  },
  getters: {
    getPhotoItemById(state) {
      // this.$store.getters.getPhotoItemById()
      return (id) => {
        return state.photos.find((photo) => {
          return photo.id == id;
        });
      };
    },
  },

  mutations: {
    login(state, payload) {
      state.token = payload.token;
      // 持久化保存 token
      // 方便下次获取
      localStorage.setItem("token", payload.token);
    },

    logout(state) {
      state.token = "";
      localStorage.removeItem("token");
    },

    updatePhotos(state, payload) {
      console.log(payload);
      state.photos = payload.photos;
    },

    updatePageInfo(state, payload) {
      state.pageSize = payload.prepage;
      state.pageTotal = payload.total;
      console.log(state);
    },
  },

  actions: {
    login({ commit }, payload) {
      // 异步的
      // action  支持返回 promise
      const { username, password } = payload;
      return fetchLogin({ username, password }).then((res) => {
        commit("login", {
          token: res.data.data.token,
        });
      });
    },

    updatePhotos({ commit }, payload) {
      const { p } = payload;
      return fetchPhotos(p).then((res) => {
        console.log(res.data);
        commit("updatePhotos", {
          photos: res.data.data.photos,
        });
        const { prepage, total } = res.data.data.page;
        commit("updatePageInfo", {
          prepage,
          total,
        });
      });
    },
  },
});

export default store;

二,配置 路由导航守卫

router文件夹下的index.js

import VueRouter from "vue-router";
import Vue from "vue";
import Photo from "../view/Photo.vue";
import Login from "../view/Login.vue";
import Detail from "../view/Detail.vue";
import store from "../store";

// 插件使用
Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/",
      redirect: "/photo",
    },
    {
      path: "/photo",
      name: "photo",
      component: Photo,
      meta: {
        requireAuth: true,
      },
    },
    {
      path: "/login",
      name: "login",
      component: Login,
    },
    {
      path: "/detail/:id",
      name: "detail",
      component: Detail,
      props: true,
    },
  ],
});

// 导航守卫
// 提前检测有没有 token
router.beforeEach((to, from, next) => {
  // 当你访问 login 页面的时候 需要拦截吗?
  // photo 页面的时候 才需要拦截
  if (to.meta.requireAuth) {
    // 看看 store 里面有没有 token
    if (store.state.token) {
      next();
    } else {
      next({
        name: "login",
      });
    }
  } else {
    next();
  }
});

export default router;


三、请求头加token 在 main.js中添加
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(  config => {    
    if (localStorage.getItem('Authorization'))
     {      
        config.headers.Authorization = localStorage.getItem('Authorization');    
     }    
    return config;  },  
    error => {    return Promise.reject(error);  
});

token的过期可以自定义

四、如果前端拿到状态码为401,就清除token信息并跳转到登录页面
localStorage.removeItem('Authorization'); this.$router.push('/login');

五、退出功能,就是清楚token就退出了,然后commit一个方法this.$store.commit(“logout”)

触发这个logout方法

logout
export default { name: "App", components: {}, created() {}, methods: { handleLogout() { this.$store.commit("logout"); this.$router.push({ name: "login", }); }, }, }; #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }

2.在store里面的index.js文件,清楚token

   logout(state) {
      state.token = "";
      localStorage.removeItem("token");
    },

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。