computed和watch之间的问题
问题描述:
需求是用户点击标题,游览器窗口中间会弹出两个小窗口,文字介绍和图片介绍。但是,由于后端数据不完整,有些文字/图片没有,要求点击标题,如果后端没有数据,弹出的窗口就隐藏,有数据就弹出窗口。
我第一时间想到的就是vuex,后端返回的数据存入状态机里,点击对应标题,computed监听提出状态机里的对应数据。
出现的问题是:computed里能提出数据,但是在里面写if判断的时候,状态机里的数据就取不出来了,也不会报错。
computed:{
user(){
return this.$store.state.planstate.feng
}
}
上面这样监听状态机里的数据,提取都没有问题
computed:{
user(){
if(this.$store.state.planstate.feng.length == 0){
this.detailToggle = true //这里就是隐藏弹窗的窗口
}
return this.$store.state.planstate.feng
}
}
上面这段代码就会出问题,提取不了状态机里面的数据,弹窗也不弹了
解决方法:
在computed监听的基础上加上watch监听
watch:{
user(news){
if(news.length>0){
this.detailToggle = true
}
else{
this.detailToggle = false
}
}
}
原因分析:
目前还没找到原因
解决方案:
使用了watch进行监听user,就可以解决