Vuex变异未更新状态

时间:2020-09-03 09:59:34

标签: javascript vue.js state vuex

在Vuejs应用程序上工作,在该应用程序中我使用Vuex进行组件之间的状态管理。在Vuex存储中,我有一个动作是从API提取一些数据(效果很好),然后将其填充到状态(通过突变) 。接下来,我使用吸气剂将更新后的状态传递给组件。

问题在于将数据从操作填充到状态时存在问题。在DOM中,我尝试通过计算属性或使用getter进行获取,但获取空字符串

Vuex商店

C:\Users\heman>docker version
Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a66213fe
 Built:             Mon Jun 22 15:43:18 2020
 OS/Arch:           windows/amd64
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a66213fe
  Built:            Mon Jun 22 15:49:27 2020
  OS/Arch:          linux/amd64
  Experimental:     true
 containerd:
  Version:          v1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
 Kubernetes:
  Version:          v1.16.6-beta.0
  StackAPI:         v1alpha3

组件

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
}

1 个答案:

答案 0 :(得分:1)

您需要先获取数据。 从vuex导入mapActions

import {mapActions, mapGetters} from 'vuex';

在组件的方法对象中引入fetchClients方法

methods:{
 ... mapActions(['fetchClients']),
}

然后在组件的已创建生命周期方法中调用fetchClients方法

created(){
 this.fetchClients();
}