基于Vuex浮点的商店值存储为字符串

时间:2017-06-19 18:48:50

标签: vue.js vuex

我在桌面上创建了Vuejs前端项目。我正在使用Vuex进行集中式状态管理。我在我的状态中有TotalAmount和Profit值,我正在尝试对这两个状态进行加法和减法运算。当然,减少工作效果,但增加功能将它们连接到状态。 我们假设:

TotalProfit:1.05465
Profit:0.0012

增加1.054650.0012上的函数返回。

Store.js文件:

const state = {
    TotalBalance: 0,
    Profit:0.00000000
};
const actions = {
    setTotalBalance(context, data) {
        context.commit('setTotalBalance', parseFloat(data).toFixed(8))
    },
    increaseTotalBalance(context, data) {
        context.commit('increaseTotalBalance', parseInt(data).toFixed(8))
    },
    decreaseTotalBalance(context, data) {
        context.commit('decreaseTotalBalance', parseFloat(data).toFixed(8))
    },
    setProfit(context, data) {
        context.commit('setProfit', data)
    },
}
const mutations = {
    setTotalBalance(state,TotalBalance){
        state.TotalBalance = Number(parseFloat(TotalBalance).toFixed(8));
    },
    increaseTotalBalance(state,Balance){
        state.TotalBalance = Number(parseFloat(state.TotalBalance ).toFixed(8))+Number(parseFloat(Balance).toFixed(8))
    },
    decreaseTotalBalance(state,Balance){
        state.TotalBalance = parseFloat(state.TotalBalance ).toFixed(8)-parseFloat(Balance).toFixed(8)
    },
    setProfit(state,Profit){
        state.Profit = Number(parseFloat(Profit).toFixed(8))
    }
}
const getters = {
    getTotalBalance: state=>{
        return state.TotalBalance
    },
    getProfit: state => {
        return state.Profit
    }
}
export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})

正如您从上面的文件中看到的那样,我尝试了许多不同的方法,但我自己找不到任何解决方案。

1 个答案:

答案 0 :(得分:2)

toFixed会返回字符串,因此您会获得连接字符串。相反,您可以+string将字符串转换为数字,并在需要显示时在getter中剪切8位数字:

const store = new Vuex.Store({
  state: {
    TotalBalance: 1.05465,
    Profit: 0.0012
  },
  mutations: {
    increaseTotalBalance(state,Balance){
      state.TotalBalance = +state.TotalBalance + +Balance;
    },
    decreaseTotalBalance(state,Balance){
      state.TotalBalance = +state.TotalBalance - +Balance;
    },
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    total: function() {
      return Number(this.$store.state.TotalBalance).toFixed(8);
    },
    profit: function() {
      return Number(this.$store.state.Profit).toFixed(8);
    }
  },
  methods: {
    inc: function() {
      this.$store.commit('increaseTotalBalance', this.profit)
    },
    dec: function() {
      this.$store.commit('decreaseTotalBalance', this.profit)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script src="https://unpkg.com/vuex@2.3.1"></script>

<div id="app">
  <p>{{ total }}, {{ profit }}</p>
  <button @click="inc">Inc</button>
  <button @click="dec">Dec</button>
</div>