JavaScript/vue.js/store:修订间差异
来自康健生活
| (未显示同一用户的8个中间版本) | |||
| 第1行: | 第1行: | ||
{{Sign}} | |||
== 引言 == | == 引言 == | ||
留白 | 留白 | ||
| 第66行: | 第67行: | ||
setFile ({ commit }, fileObj) { | setFile ({ commit }, fileObj) { | ||
commit('updateFile', fileObj) | commit('updateFile', fileObj) | ||
}, | }, | ||
deleteFile ({ commit }, url) { | deleteFile ({ commit }, url) { | ||
| 第119行: | 第117行: | ||
state.fileList.splice(deteleIndex, 1); | state.fileList.splice(deteleIndex, 1); | ||
}, | }, | ||
} | } | ||
export default { namespaced: true, state, mutations, actions } | export default { namespaced: true, state, mutations, actions } | ||
| 第158行: | 第153行: | ||
}); | }); | ||
}</syntaxhighlight>}} | }</syntaxhighlight>}} | ||
流程如下: | |||
[[文件:Vue new store 5.png|600px|none|无|Vue new store 5]] | |||
可以感受到错位的地方在于我的store 中已经更新了值,但是页面组件取的 store 值是已经初始化,并且更新为从后端拿到新值并存入 store 后的值。简单说就是两个组件: | |||
* 子组件离开页面前时执行 <syntaxhighlight lang="javascript" inline> | |||
this.$store.dispatch('file/initFile');</syntaxhighlight> | |||
* 父组件加载新页面时执行 <syntaxhighlight lang="javascript" inline> | |||
store.dispatch('file/setFile', Object.assign({},SessionData))</syntaxhighlight>; | |||
我们期望的执行顺序是: | |||
[[文件: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> | |||