如何从Vuex存储中的外部API设置状态

时间:2019-05-24 11:34:27

标签: vue.js axios vuex

在store.js中,我初始化了一个对象

let exchangeRates = {
    GBPtoUSD: 0, // American dollar
    GBPtoEUR: 0, // Euro
    GBPtoCAD: 0, // Canadian dollar
    GBPtoINR: 0, // Indian rupee
    GBPtoCHF: 0 //Swiss franc
}

然后我用

设置其值
function getExchangeRates() {
    return axios.get('https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD,EUR,CAD,CHF,INR')
                .then((response)=> {
                    exchangeRates.GBPtoUSD = response.data.rates.USD;
                    exchangeRates.GBPtoEUR = response.data.rates.EUR;
                    exchangeRates.GBPtoCAD = response.data.rates.CAD;
                    exchangeRates.GBPtoINR = response.data.rates.INR;
                    exchangeRates.GBPtoCHF = response.data.rates.CHF;
                })
                .catch((error)=> {console.log(error)})
}

我的州获得了这样分配的值

state: {
        GBPtoUSD: exchangeRates.GBPtoUSD, // American dollar
        GBPtoEUR: exchangeRates.GBPtoEUR, // Euro
        GBPtoCAD: exchangeRates.GBPtoCAD, // Canadian dollar
        GBPtoINR: exchangeRates.GBPtoINR, // Indian rupee
        GBPtoCHF: exchangeRates.GBPtoCHF //Swiss franc
    }

然后我设置吸气剂,例如

getGBPtoUSD: state => {
            return state.GBPtoUSD;
        },

问题是,稍后我要像这样在我的组件中调用该getter

...mapGetters( [ "getGBPtoUSD" ] )
<li class="list-group-item py-3 ">
            {{ precise(userInputPrice) }}£ in USD is
            {{ precise(userInputPrice * getGBPtoUSD()) }} US dollars
</li>

我将getGBPtoUSD设置为0-初始状态。

如何解决此问题,以便实际上从外部分配状态值?我这样做的方法显然行不通。

EDIT1

这样做

exchangeRates.GBPtoUSD = response.data.rates.USD;
      console.log(exchangeRates.GBPtoUSD)

记录大约1.27的正确值。那我在哪里搞砸了?

1 个答案:

答案 0 :(得分:0)

我已经制作了这个示例,说明如何使用axios从外部服务设置状态

// main.js

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import axios from "axios";

Vue.config.productionTip = false;

Vue.use(Vuex);

const store = new Vuex.Store({
  // create the state to store the data
  state: {
    todo: {}
  },

  // make an asynchronous call to get the data
  actions: {
    getTodoItem(state, index) {
      return axios.get(`https://jsonplaceholder.typicode.com/todos/${index}`);
    }
  },

  // set data in state
  mutations: {
    setTodo(state, value) {
      Vue.set(state, "todo", value);
    }
  }
});

new Vue({
  store, // loads the store
  render: h => h(App)
}).$mount("#app");
<!-- App.vue -->

<script>
import { mapState, mapActions, mapMutations } from "vuex";

export default {
  computed: {
    ...mapState(["todo"]),
    hasTodo() {
      return Object.keys(this.todo).length;
    }
  },
  methods: {
    ...mapActions(["getTodoItem"]),
    ...mapMutations(["setTodo"]),

    async getTodo() {
      // random number between 1 and 200
      const index = Math.floor(Math.random() * 200) + 1;
      const { data } = await this.getTodoItem(index);
      this.setTodo(data);
    }
  },
  mounted() {
    this.getTodo();
  }
};
</script>


<template>
  <div id="app">
    <div v-if="hasTodo">Todo: {{ todo.title }}</div>
    <b v-else>Loading..</b>
  </div>
</template>

https://codesandbox.io/s/vue-template-y69be