JavaScript/vue.js/store
来自康健生活
< JavaScript | vue.js
引言
留白
store更新
视图未更新
今天做上传组件遇到一个问题,store 值更新后,组件中的 store 并没有更新。
先列出后端接口(接口和字段为虚拟,并非真实)
- getSessionId 获取页面级别的上传标识
- putFile 上传文件
流程图如下

现在的问题是上传结束后,store 更新后,组件中的 store 值依然是上次的值(等于视图组件值没有更新)。
以下是尝试后的失败的方法
data () {
return {
sessionid: this.$store.state.file.sessionid
};
},
computed: {
watchSid () {
// 需要监听的数据
return this.$store.state.file.sessionid
}
},
watch:{
watchSid:{
handler (val){
this.sessionid = val
},
deep:true,
immediate:true
}
},
我试图通过监听 store 的值变化来更新组件的 data(通过 data 中转并缓存 sessionId),并没有管用。
所以换一个思路,或许不是取值过程中出现错误,而是其他地方导致问题,先查看store 文件
store/file.js
/**
* TODO 用户相关的 store
* @author kangkk
*/
const __init__ = {
sid: 99999,
id: 99999,
docFrom: 'orig',
agreement: false,
bid: '0',
category: 'cs',
content: '',
title: '',
fileList: [],
photoList: []
}
export const state = () => {
return Object.assign({}, __init__)
}
const actions = {
initFile ({ commit }) {
commit('initFile')
},
setFile ({ commit }, fileObj) {
commit('updateFile', fileObj)
},
getFile ({ commit }) {
commit('getFile')
},
deleteFile ({ commit }, url) {
commit('deleteFile', url)
},
updateFileList ({ commit }, fileList) {
commit('updateFile', {
fileList: fileList
})
},
updatePhotoList ({ commit }, photoList) {
commit('updateFile', {
photoList: photoList
})
},
addFile ({ commit }, fileItem) {
commit('addFile', fileItem)
},
addPhoto ({ commit }, photoItem) {
commit('addPhoto', photoItem)
},
}
const mutations = {
initFile (state) {
Object.assign(state, __init__)
},
updateFile (state, fileObj) {
Object.assign(state, fileObj)
},
addFile (state, fileItem) {
const newFileList = state.fileList.push(fileItem)
Object.assign(state, {
fileList: newFileList
})
},
addPhoto (state, photoItem) {
const newPhotoList = state.photoList.push(photoItem)
Object.assign(state, {
photoList: newPhotoList
})
},
deleteFile (state, url) {
const deteleIndex = state.fileList.findIndex((o) => {
const tmpUrl = o['url'] || o['fileUrl'];
if (tmpUrl === url) {
return o;
}
});
state.fileList.splice(deteleIndex, 1);
},
getFile (state) {
return state
}
}
export default { namespaced: true, state, mutations, actions }
重新走一遍逻辑,截图如下
| 上传过程中 sesion 缓存的值 | 上传成功后刷新页面 session 缓存的值 | 上传成功后页面中 store 的值 |
|---|---|---|
这里直接看到抛错的问题点在 session 缓存的值(9999 这个预设值,出现预设值说明已经抛错,即新的 sesionId -> sid 并没有存储到 store中),但是页面组件又显示 sessionId 已经更新,那么问题的节点已经找到。
No categories


