JavaScript/vue.js/store:修订间差异
来自康健生活
| (未显示同一用户的5个中间版本) | |||
| 第1行: | 第1行: | ||
{{Sign}} | |||
== 引言 == | == 引言 == | ||
留白 | 留白 | ||
| 第155行: | 第156行: | ||
流程如下: | 流程如下: | ||
[[文件:Vue new store 5.png|600px|none|无|Vue new store 5]] | [[文件:Vue new store 5.png|600px|none|无|Vue new store 5]] | ||
可以感受到错位的地方在于我的store 中已经更新了值,但是页面组件取的 store | 可以感受到错位的地方在于我的store 中已经更新了值,但是页面组件取的 store 值是已经初始化,并且更新为从后端拿到新值并存入 store 后的值。简单说就是两个组件: | ||
* 子组件离开页面前时执行 <syntaxhighlight lang="javascript" inline> | * 子组件离开页面前时执行 <syntaxhighlight lang="javascript" inline> | ||
| 第165行: | 第166行: | ||
[[文件:Vue new store 6.png|600px|none|无|Vue new store 6]] | [[文件:Vue new store 6.png|600px|none|无|Vue new store 6]] | ||
但实际情况却是这样: | |||
[[文件:Vue new store 7.png|600px|none|无|Vue new store 7]] | |||
实际上由于加载新页面时是使用 <code>async asyncData</code> 在服务端跑接口,导致 session 更新 store 与 asyncData 中接口更新 store 是一个并行竞争问题。所以抛错。 | |||
解决办法: | |||
将父组件的初始化 store 放到 mounted 中执行,并在此之前更新本地 session | |||
<syntaxhighlight lang="javascript"> | |||
mounted () { | |||
let storeCache = sessionStorage.getItem("storeCache") | |||
if(storeCache){ | |||
const tmp = JSON.parse(storeCache) | |||
if(tmp.file){ | |||
// 刷新 session 中缓存的 file 对象 | |||
sessionStorage.setItem("storeCache", JSON.stringify(Object.assign(tmp, { | |||
file: Object.assign(tmp.file, this.sessionData) | |||
}))) | |||
} | |||
} | |||
this.$store.dispatch('file/setFile', Object.assign({}, this.sessionData)); | |||
},</syntaxhighlight> | |||