在您发送了一个改变了状态的异步操作后,在 vuex 中调用 getter 的正确方法是什么?
我创建了一个示例片段来说明我的意思。如您所见,getLastNameByName()
失败,因为 state.persons
为空。奇怪的是,如果我在那个 getter 中打印 state.persons
,它会在 api 调用后打印数组。
预期的行为是 getLastNameByName('John')
返回 {name: 'John', lastname: 'Smith'}
const store = new Vuex.Store({
state: {
persons: []
},
getters: {
getLastNameByName: (state) => (name) => {
// console.log(state.persons) returns the state, yet I cannot call .find on it
return state.persons.find(element => {
return element.name === name
}).lastname
},
},
mutations: {
setPersons: (state, payload) => {
state.persons = [...payload]
}
},
actions: {
async getPeople({commit}) {
return new Promise(function(resolve, reject) {
setTimeout(async () => {
commit('setPersons', [{
name: 'John',
lastname: 'Smith'
}, {
name: 'Sarah',
account: 'Appleseed'
}])
resolve();
}, 1000)
})
}
}
})
new Vue({
store,
el: '#app',
mounted() {
this.$store.dispatch('getPeople').then( () => {
console.log(this.$store.getters.getLastNameByName('John'))
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
</div>
最佳答案
setTimeout() 不返回等待对象。检查 promise :
const store = new Vuex.Store({
state: {
persons: []
},
getters: {
getLastNameByName: (state) => (name) => {
return state.persons.find(element => {
return element.name === name
}).lastname
},
},
mutations: {
setPersons: (state, payload) => {
state.persons = [...payload]
}
},
actions: {
async getPeople({commit}) {
return new Promise(function(resolve, reject) {
setTimeout(async () => {
commit('setPersons', [{
name: 'John',
lastname: 'Smith'
}, {
name: 'Sarah',
account: 'Appleseed'
}])
resolve();
}, 1000)
})
}
}
})
new Vue({
store,
el: '#app',
mounted() {
this.$store.dispatch('getPeople').then(() => {
console.log(this.$store.getters.getLastNameByName('John'));
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
</div>
无论如何,直接处理对存储的异步调用不是正确的方法。我认为在这种情况下更好的解决方案是 watch
存储状态或使用 computed
属性。
关于asynchronous - 异步api调用后如何使用vuex getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777258/