vue用户信息最适合存储在哪里(史上最简洁一次搞定)
** 1.store.js actions里面调用用户信息接口把湖区到的接口存储到vuex**
actions:{
async getUserInfos(context){
try{
//接口复用上篇文档有些
const res = await getUserInfo()
//对数据进行处理(处理头像我们直接不会返回http地址,会返回uuid 自己再调用下载接口)
//对之前的uuid进行存储修改信息会用到
res.avatarUuid = res.avatar
res.backgroundUuid = res.background
//下载图片的接口
await getFilesPath(res, ['avatar', 'background'])
context.commit('setUserInfo',res)
}catch(e){
//TODO handle the exception
}
}
}
2.store.js 定义存储的用户信息对象
state:{
userInfo:{}
},
mutations:{
setUserInfo(state,userInfo){
state.userInfo={ ... userInfo}
//这里存储这是为了方便查看返回数据也可以不存
window.localStorage.setItem("userInfo", JSON.stringify(state.userInfo))
},
getUserInfos(state){
state.userInfo = window.localStorage.getItem("userInfo")
}
}
3.在main.js 定义全局方法方面页面应用
import store from "./store/index"
Vue.prototype.$updateUserInfo=async function(){
await this.$store.dispatch("getUserInfos")
}
new Vue({
store,
render: h => h(App),
}).$mount('#app')
4.在需要获取或者更新用户信息的地方调用
5.在用到的页面实时获取userInfo的信息
import { mapState } from "vuex"
//计算属性里面监听
computed:{
...mapState(["userInfo"])
}
6.在html页面展示