标签:data 引用 方法 pos json 产生 gif 用户信息 home
首先设计的是登录成功后端产生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
标签:data 引用 方法 pos json 产生 gif 用户信息 home
原文地址:https://www.cnblogs.com/Jack-cx/p/12081702.html