javascript - 如何访问 Vuex 动态状态属性?
问题描述
如何使动态属性添加到 Vuex 状态响应?当调用任何未预定义的状态属性时,getter和操作undefined
的结果都会在刷新时返回。
Vuex 商店
interface State {
...
profile: { [key: string]: any }
}
export default createStore<State>({
state: {
...
profile: {},
},
getters: {
name: state => state.profile.name
},
mutations: {
mSetUserProfile: ( state, payload ) => {
Object.assign(state.profile, payload),
}
},
actions: {
aSetUserProfile: ({ commit }) => {
db.collection(foo)
.doc(bar)
.get()
.then(response => commit('mSetUserProfile', response))
},
aGetName: ({state}) => state.profile.name
}
})
应用程序.vue
setup(){
...
store.dispatch('aSetUserProfile')
store.dispatch('aGetName') // returns 'undefined'
store.getters.name // returns 'undefined'
...
}
解决方案
aGetName
应该是吸气剂而不是动作。
aSetUserProfile
包含一个错误,它不允许内部承诺被链接,它应该是:
aSetUserProfile: ({ commit }) => {
return db.collection(foo) ...
动作是异步的,它们的结果不应该立即可用。他们可以通过使用等待组件初始化<suspense>
:
async setup() {
await store.dispatch('aSetUserProfile')
...
或者这可以在onMounted
.
推荐阅读
- azure - 遍历列表并获取列表中的每个值
- python - 我将推文中的单词限制为内容单词现在我想将单词转换为小写并添加带有下划线的 POS
- reactjs - 使用 react 钩子时如何在 react-chartjs 中使用动态数据?
- mysql - 我可以在 CodeIgniter 的模型上使用两个表吗?
- python - asyncpg 错误:Heroku 中的“主机没有 pg_hba.conf 条目”
- c# - C# 应用程序在任务栏中最小化时不工作
- regex - Azure 数据资源管理器,Kusto:extract() 中的正则表达式在语义上不正确
- php - 修改预先存在的分类
- angular - 当api在Angular中返回空结果集时显示未找到结果?
- javascript - 检测嵌入式演示文稿中的最后一张幻灯片(来自 Google Slides、SlideShare 等的 iframe)