本地存储 (vuex,token持续有效)

本地存储 (vuex,token持续有效)

我这里用的是封装的loca.js(localStorage的方法)
文件js放在src的里面和app.vue同级

export default{
    
    
           //存储
           save(key,val){
    
    
               localStorage.setItem(key,JSON.stringify(val))
           },
           //取出 
           fetch(key){
    
    
               return JSON.parse(localStorage.getItem(key)) || []
           }
        }

把需要存储的token通过commit方法传给store

 this.$store.commit("login",res.data.data.token)

store>index.js引入封装好的loca,例如(import loca from ‘./loca’)

 mutations:{
    
    
        login(state,token){
    
    
            state.token=token
            loca.save('chx',state.token)
        }
    }

页面app取出(引入封装好的loca)

created() {
    
    
    let token=loca.fetch('chx')
    this.$store.commit('login',token)
  }

| | |
src下创建的axios封装的固定路由config文件下index.js

const config={
    
    
    baseUrl:'固定路径'  
    //baseUrl  封装的路由名称
    }
export default config

在utils下的http.js(axios封装接口)

//引入import config from "../config"
//请求在到达服务器之前,先会调用use中的这个回调函数来添加请求头信息
Axios.interceptors.request.use(config=>{
    
    
    //为请求头对象,添加token验证的Authorization字段
    config.headers.Authorization = loca.fetch("chx")
    return config
  })

猜你喜欢

转载自blog.csdn.net/Sunshine_GirlXue/article/details/103001526