vue添加攔截器(身份認證)以及cookie認證


一、安裝vuex和cookies

npm install vuex --save
npm install vue-cookies --save

在全局變量文件中引用

import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'vue-cookies'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username:  Cookie.get("username"),
    token:  Cookie.get("token"),
  },
  mutations: {
    saveToken: function (state, userToken) {
      state.username = userToken.username;
      state.token = userToken.token;
      Cookie.set("username", userToken.username, "20min");
      Cookie.set("token", userToken.token, "20min")
    },
    clearToken: function (state) {
      state.username = null;
      state.token = null;
      Cookie.remove("username");
      Cookie.remove("token");
      // this.$router.push({name: "micro"});
    },
  }
})

二、在vue文件中將登陸數據存入cookie

創建出發事件:
<button @click="toLogin">提交</button>

創建觸發的方法
methods:{
        toLogin(){
          var that = this;
          this.$axios.request({
            url: "http://127.0.0.1:8000/api/v1/auth/",
            method: "POST",
            data: {username: this.username, password: this.password},
            headers: {
              "Content-Type":"application/json",
              "k1":"v1",
            }
          }).then(function (arg) {
            if (arg.data.code === 1000){
              console.log(arg.data);
              // that.$store.state.token = arg.data.token;
              // that.$store.state.username = that.username;
         // 第一個參數saveToken為這里調用的全局變量文件中定義的方法,第二個參數為傳入的變量 that.$store.commit(
"saveToken",{"username": that.username,"token":arg.data.token}); }else { console.log(arg.data) } }).catch(function () { console.log("請求失敗!") }) } }

三、首頁中如何判斷cookie中是否含有用戶token

<div v-if="this.$store.state.token">
      <a>{{this.$store.state.username}}</a>
      <a @click="logout">注銷</a>
</div>
<div v-else>
      <router-link to="/login">登陸</router-link>
</div>

四、在路由文件中添加認證

index.js文件中
{
      path: '/micro',
      name: 'micro',
      component: Micro,
      meta:{
        "requireAuth": true,
}

在main.js中
router.beforeEach(function (to, from, next) {
  if (to.meta.requireAuth){
    if (store.state.token){
      next()
    }else {
      next({name: "login",query:{backUrl:to.fullPath}})
    }
  } else {
    next()
  }

});

配置后,如果登陸成功,應該自動進入想要進入的頁面,需要在toLogin()方法中加入刷新頁面的功能

var url = that.$route.query.backUrl;
              // console.log(url)
              if (url){
                that.$router.push({path:url})
              }else {
                that.$router.push({path:"index"})
              }

五、頁面加載后,自動向后端提交token

methods: {
          initMicro(){
            var that = this;

            this.$axios.request({
              url: "http://127.0.0.1:8000/api/v1/micro/",
              method: "GET",
              params: {
                token: this.$store.state.token,
              }
            }).then(function (ret) {
              if (ret.data.code === 1000){
                that.micro_title = ret.data.data
              }
            })
          }
      }

后端接收到token后,從數據庫查詢,如果能夠獲取結果,則返回正確的值和數據,取出數據后,即可渲染模板。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM