【发布时间】:2020-12-22 13:12:58
【问题描述】:
在一个 Vuejs 应用程序上工作,我使用 Vuex 在组件之间进行状态管理。在 Vuex 商店中,我有一个操作从 API 获取一些数据(工作正常)然后将其填充到状态(通过突变) .接下来,我使用 getter 将更新后的状态传递给组件。
问题是从操作向状态填充数据时出现问题。在 DOM 中,我尝试通过计算属性或使用 getter 获取但得到空字符串
Vuex 商店
const getDefaultState = () => {
return {
clientDeposit: ''
}
}
//state
const state = getDefaultState();
//getters
const getters = {
getDeposit: (state) => state.clientDeposit
}
//actions
const actions = {
fetchClients({ commit}) {
const clientId ="23"
axios.post('/api/motor/fetchClients', {
ClientId: clientId,
})
.then((response)=> {
//console.log(response); //returns data
const deposit = response.data;
commit('setIpfDeposit', deposit);
})
}
}
//mutations
const mutations = {
setIpfDeposit: (state, value) => (state.clientDeposit = value)
}
export default {
state,
getters,
actions,
mutations
}
组件
<template>
<div>
<button onclick="fetchClients()">Fetch Clients</button>
Deposit (Via computed property) : {{ fetchDeposit }}
Deposit (from getter) : {{ getDeposit }}
</div>
</template>
<script>
import { mapGetters , mapActions } from "vuex";
import axios from "axios";
export default {
name: "",
data() {
return {
}
},
computed: {
...mapGetters([
"getDeposit"
]),
fetchDeposit(){
return this.getDeposit
},
},
methods:{
...mapActions([
"fetchClients"
])
}
};
</script>
<style scoped>
</style>
【问题讨论】:
标签: javascript vue.js state vuex