【问题标题】:Vuex Mutation not updating the StateVuex Mutation 不更新状态
【发布时间】: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


    【解决方案1】:

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

    import {mapActions, mapGetters} from 'vuex';
    

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

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

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

    created(){
     this.fetchClients();
    }
    

    【讨论】:

    • @F Kilng,,请您帮忙,我省略了为获取客户数据而单击的按钮。我已经编辑了我的问题。请看一看。实际上主要问题是从动作中填充 vuex 状态。这样我就可以通过 Vuex getter 将数据传递给 Dom
    • 尝试使您的商店中的 fetchClients 操作异步。
    • 要使 fetchClients 操作异步,只需在操作名称前添加单词 async 并在 axios api 调用之前等待 async fetchClients ({commit}){ await axios.post()}
    猜你喜欢
    • 2019-02-24
    • 2021-06-19
    • 2018-10-19
    • 2020-11-23
    • 2023-03-16
    • 2020-05-18
    • 2019-08-08
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多