Vue,Vuex-这是使用过滤器中存储的好方法

时间:2019-11-25 16:10:16

标签: vue.js vuex

我是Vue的新手,无法理解一些简单的知识。 我有基于Vuex的商店。每隔15秒,我就会从API中获取USDEUR货币汇率。 在我的组件中,我有固定的美元价格,并且必须用欧元价格代替。 这是使用过滤器的好方法吗?以及如何实施?

商店:

actions: {
   async fetchRate ({ commit }) {
     let rate = await Promise.all([getUSDEURRate()])
     commit('setUSDEURRate', rate)
   }
}
getters: {
   return getCurrencyRate(state)
}

组件(我在页面上多次使用了此部分)

<div>The price is {{ priceInUsd | toEuro }}</div>

main.js

Vue.filter('toEuro', value => {
  return value * HERE_NEED_TO_GET_EURO_RATE_FROM_STORE
})
new Vue({
  store,
  render: h => h(App),
  created () {
    this.$store.dispatch('fetchRate')
    setInterval(() => {
     this.$store.dispatch('fetchRate')
    }, 15000)
  }
}).$mount('#app')

谢谢您对代码结构的帮助。

1 个答案:

答案 0 :(得分:1)

根据VueJS文档:

  

Vue.js允许您定义可用于应用通用的过滤器   文本格式

(来源:https://vuejs.org/v2/guide/filters.html

这不是格式问题,因此在这种情况下,我不会使用过滤器

您可以这样做:

const store = new Vuex.Store({
  state: {
    rates: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    currentRate: 0
  },
  mutations: {
    setCurrentRate(state, next) {
      if (next) {
        state.currentRate += 1
      } else {
        state.currentRate = 0
      }
    }
  },
  actions: {
    fetchRate(ctx) {
      if (ctx.state.currentRate < 9) {
        ctx.commit('setCurrentRate', 1)
      } else {
        ctx.commit('setCurrentRate', 0)
      }
    }
  }
})
new Vue({
  store,
  el: "#app",
  data: {
    amountInUSD: 0,
    currentRate: 1 // only for displaying the rate
  },
  computed: {
    amountInEUR() {
      // the conversion calculation is here:
      return this.amountInUSD * this.$store.state.rates[this.$store.state.currentRate]
    }
  },
  mounted() {
    setInterval(() => {
      this.$store.dispatch('fetchRate')
      this.currentRate = this.$store.state.rates[this.$store.state.currentRate]
    }, 2000)
  }
})
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="amountInUSD" type="number"> USD<br />
  <div>Current rate: {{currentRate}}</div><br />
  <div>Current value in EUR: {{amountInEUR}} EUR</div>
</div>

在代码段中,我创建了一个模拟数据集和函数,但要点是,转换计算是在 compute 属性中完成的。

如果不止一个组件使用这些值,也可以将整个商品移入商店。