情景: 一进入首页就会调后台接口去数据库里查询有没有数据,如果有得到数据就把它显示在首页上。接口无报错,且数据能打印出来,但是首页就是没有展示数据,无论怎么刷新都不行,进入其他页面在返回时发现有数据了。怀疑与生命周期有关。
一开始在首页的data()里面是这样定义username属性的:
username: this.$store.state.user.username === '' ? '游客' : this.$store.state.user.username
然后在mounted()里面diapatchstore里面的actions,在actions里面调接口并得到返回值,然后在mutations里改变state里面对应属性的值。但是值改变了,页面上的数据却没变。问题就在这里。无论怎么刷新都不管用!
后来打开之前考下来的其他项目参考,发现它们在页面上的data()里面初始化的属性基本上都是没有值的。然后我便仿着来,同时在mounted()方法里加上了
this.username = this.$store.state.user.username
结果仍然没有。
然后放弃了在actions里面调后台接口的想法,照着之前那位高仿饿了么的大神的写法在页面上直接调后台接口:
getUserInfo(this.$store.state.user.userid).then(res => {
console.log(res)
if (res.data.success) {
this.$store.state.user.username = res.data.data.username
this.$store.state.user.phone = res.data.data.phone
this.username = this.$store.state.user.username
}
})
搞定了。
至于原理我就有点不大了解了,只能来社区问了。一开始想着是不是生命周期的原因,但是我代码写在mounted()里面难道不比data()快?
心有法竹
繁华开满天机
桃花长相依
随时随地看视频慕课网APP
相关分类