First, the design is a successful logon token generated from the back, the front end out on the Local Storage, tape easy to each request after the default token and where the user information fetch
And main.js sibling build store.js file, the code is as follows
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
This time coupled with the global header autograph requests we would not pass for a header token in the project configuration in 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); } )
Stored-value projects
<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; // successful login into the store generated token the this $ store.commit ( "$ _ setStorage", res.data.token);. Remove // After a successful login user name into the Store the this $ store.commit ( "$ _ setAccount." , res.data.account); . $ router.push the this ({path: "/ Home"}); } }
Remove Local Storage value stored in the project
In reference 1.template
{{this.$store.state.account}}
2. The reference method
this.$store.state.accoun