我是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')感谢您在代码结构方面的帮助。
发布于 2019-11-26 07:58:19
根据VueJS文档:
Vue.js允许您定义可用于应用普通文本格式的筛选器。
(资料来源:https://v2.vuejs.org/v2/guide/filters.html)
这不是格式化问题,所以在本例中我不会使用filters。
你可以这样做:
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>
在这个片段中,我创建了一个模拟数据集和函数,但重点是转换计算是在计算的属性中完成的。
如果有多个组件使用这些值,则还可以将整个组件移动到存储区中。
https://stackoverflow.com/questions/59035862
复制相似问题