简体   繁体   中英

Vue.js - Value is concatenated instead of added

I have an app that uses Vue.js. The app just has a list of items. Each item has a price. I want to calculate the total of all of the items in the list. The list may change, and in some cases, will come from a web service. So, I want to use a watcher. Still, when calculating the total, something odd is happening.

Instead of the cost of each item getting added together. It looks like the values are getting concatenated. So, if the first item has a cost of 0.76 and the second item has a cost of 2.18, the result is "00.762.18". You can see the result for yourself in this Fiddle . My Vue is defined like this:

new Vue({
  el: '#myApp',
  data: {
    list: [
      { name: 'Golf Ball', cost: 3.49 },
      { name: 'Tennis Ball', cost: 0.75 }
    ],
    total: 't.b.d'
  },
 watch: {
   list: function() {
     this.updateTotal();
   }
 },  
  methods: {
    updateTotal: function() {
      this.total = 0.0;
      for (var i=0; i<this.list.length; i++) {
        console.log('cost: ' + this.list[i].cost);
        this.total += this.list[i].cost;
      }
      console.log(this.total);
    },

    setCosts: function() {
      for (var i=0; i<this.list.length; i++) {
        var d = Math.floor(Math.random() * 3);
        var c = Math.floor((Math.random() * 99)) / 100;

        var item = this.list[i];
        item.cost = (d + c).toFixed(2);
        Vue.set(this.list, i, item);                                          
      }      
    }
  }
})

I don't understand why this is happening. You can repeatedly see it happening by clicking the "Set Item Costs" button. It's like Vue is seeing the total as a string, but, as shown in the updateTotal function, I set it as a number. Even when total is initialized with a number, it still treats it like a string. What am I doing wrong?

Calling toFixed() in your setCosts method returns a string. So you are adding two strings, which results in a concatenated string.

If you want item.cost as a numeric value, you can use the unary plus like this:

item.cost = +((d + c).toFixed(2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM