vue单页面应用,在整个app入口,需要调用获取用户信息的接口,这个接口只调用一次,怎样能够在多个组件中获取到这个接口完成的通知。
app.vue
export default {
mounted() {
this.userInfo().then(res => {
if (res.code === 200) {
// 具体的操作
}
});
},
methods: {
...mapState(['userInfo'])
}
};
其他组件 在mounted 获取不到userInfo
export default {
mounted() {
this.userInfo // 这里获取用户信息为空,怎样能获取到用户信息呢
},
methods: {
...mapState(['userInfo'])
}
};
已尝试的解决方案。
第一种通过$watch
监听userInfo
watch: {
userInfo(newValue){
if(newValue.username){
// 具体执行函数
}
}
},
第二种 在入口处用loading状态来控制,当在入口处action结束时,通过v-if控制渲染,
这样存在的问题是当这个接口挂了,整个页面都是空白的
<div id="app">
<template v-if="loading">
<router-view class="child-view"></router-view>
</template>
</div>
export default {
data(){
return {
loading:false
}
},
mounted() {
this.userInfo().then(res => {
this.loading=true
})
},
methods: {
...mapState(['userInfo'])
}
}
想问一下,有其他更好的办法吗?
用计算属性就可以了,当userinfo更新时会自动触发组件数据更新