赞
踩
什么是 vuex ?
面对一个储存状态数据的工具时, 有几个方面的问题我们马上可以想到的
vuex的优点:
vuex的缺点:
项目中遇到vuex此缺点的处理
场景 - 用户登录,提交订单之后,跳转到付款页,在created发送axios请求,获取付款二维码字符串等信息。但是刷新之后,请求响应是401 Unauthorized,看headers是Bearer undefined。
created: function () {
this.$axios({
url: "/airorders/" + this.$route.query.id,
headers: {
Authorization: "Bearer " + this.$store.state.user.userInfo.token,
},
}).then((res) => {
console.log(res.data);
});
},
原因分析 - 不可以直接在created获取数据,因为直接跳转过来没问题,但是一刷新,vuex的token就没有了,created的时候localstorage的token还没回来。
行动
watch: {
"$store.state.user.userInfo.token": {
handler: function () {
if (this.$store.state.user.userInfo.token) {
this.$axios({
url: "/airorders/" + this.$route.query.id,
headers: {
Authorization: "Bearer " + this.$store.state.user.userInfo.token,
},
}).then((res) => {
console.log(res.data);
},
immediate: true,
},
},
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。