简体   繁体   中英

Vue computed properties, issues with addition vs concatenation

Just learning Vue and I stumbled upon an interesting behavior, I'd like to know why this happens and how to avoid it.

<template>
  <div>
    <input type="number" v-model="a" style="color: white" />
    <input type="number" v-model="b" style="color: white" />
    <p style="color: white">{{ c }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      a: 1,
      b: 2
    };
  },
  computed: {
    c: function() {
      return this.a + this.b;
    }
  }
};
</script>

On first render, 'c' is displayed as '3', which is what I would expect. If I change one of the inputs, however, the two numbers are concatenated. For example if I changed 'a' to '11', my expected value would be 13, but I'm getting '112'. Why does this happen?

Just use Number object constructor in order to make the sum:

  computed: {
    c: function() {
      return Number(this.a) + Number(this.b);
    }
  }

the two operands are considered as strings which will be concatenated when you try to put + between them, in order to avoid that default behavior try to use Number constructor or parseInt , parseFloat function to change the behavior to sum operation.

or try to use number modifier in v-model directive like:

<input type="number" v-model.number="b" style="color: white" />

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