vuex配置token和用戶信息


首先設計的是登錄成功后端產生token,前端取出放在Local Storage,便於后面每個請求默認帶上這里的token以及取用戶相關信息

 

和main.js同級建store.js文件,代碼如下

import Vue from 'vue'
import Vuex from 'vuex'
// import {getproductByIndex} from '@/data/getdata.js'
 
Vue.use(Vuex)
const key ='token'
const account_key = 'account'

const store =new Vuex.Store({
 state(){
   return{
     token:localStorage.getItem('token') ? localStorage.getItem('token'):'',
     account:localStorage.getItem('account') ? localStorage.getItem('account'):''
    //  賬號
    
   }
 },
  getters:{
    getSortage:function (state) {
      if(!state.token){
        state.token =JSON.parse(localStorage.getItem(key))
      }
      return state.token
    },
    getaccount: function(state){
      state.account=JSON.parse(localStorage.getItem(account_key))
      return state.account
    }
  },
  mutations:{
   $_setStorage(state,value){
     state.token =value;
     localStorage.setItem(key,value)
    //  localStorage.setItem(key,JSON.stringify(value))
   },
   $_setAccount(state,account_va){
     state.account =account_va
     localStorage.setItem("account",account_va)

    //  localStorage.setItem(account,JSON.stringify(account))
   }
  },
})
export default store

 

這時候再加全局header簽名我們在項目中請求就不用針對header傳token了,在main.JS配置

// 全局header簽名 
axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.common['token'] = store.state.token
    }
    return config;
  },
  error => {
    //請求錯誤
    return Promise.reject(error);
  }

)

  

 

項目中存值

<script>

import store from "../store";
export default {
  name: "login",
  components: {

  },
methods:{
login(){
if (this.account == "" || this.pwd == "") {
        this.$message.warning("請輸入賬號或密碼");
      } else if (this.account && this.pwd) {
        let data = { account: this.account, password: this.pwd };
        this.$axios
          .post("/user/login/", data)
          .then(res => {
            if (res.data.status == 200) {
              this.$message.success(res.data.message);
              this.sendKey.userccount = res.data.account;
              this.sendKey.usertoken = res.data.token;
              //         登錄成功產生token放到store
              this.$store.commit("$_setStorage", res.data.token);
              //         登錄成功后取出用戶名放到store
              this.$store.commit("$_setAccount", res.data.account);

              this.$router.push({ path: "/home" });





}



}

  

 

在項目中取出Local Storage存的值

1.template中引用

{{this.$store.state.account}}

2.方法引用

this.$store.state.accoun


免責聲明!

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



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