Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent 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>

Upon initial display, 'c' shows as '3', which aligns with my expectations. However, upon altering one of the inputs, the two values get concatenated instead of computed. For instance, if I modify 'a' to '11', I anticipate the value to be 13, but instead I receive '112'. What is causing this behavior?

Answer №1

To calculate the sum, you can utilize the Number object constructor like this:

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

When using the + operator between two operands considered as strings, they will be concatenated. To prevent this default behavior, it is recommended to use the Number constructor, or functions like parseInt and parseFloat to change the operation to addition.

Alternatively, you can apply the number modifier in the v-model directive like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to retrieve form data from a separate file

I am struggling with my HTML and JavaScript files to collect data. Despite my efforts, the function is not executing properly. Below is the code I have been working on: HTML File : <form class="form-newsletter"> <div class="form-group"> ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Restrictions of Vue Data Objects

I'm currently pondering the optimal amount of data to store in a Vue data object. Imagine I have over 4,000 objects structured like this: personWithAppointment = { id: 1, appointment_id: 1, first_name: 'Jim', last_name: 'Jim&ap ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

Troubleshooting a Bootstrap 4 Dropdown issue within a Laravel-Vue single page application

Spa.blade.php file <!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <title>SPA</title> <link href="https://fonts.googleapis.com/css?family=Lato:300,300i,4 ...

Responses were buried beneath the inquiries on the frequently asked questions page

My FAQs page is in pure HTML format. The questions are styled with the css class .pageSubtitle, and the answers have two classes: .p1 and .p2. Here's an example: <p class="pageSubtitle">Which Award should I apply for?</p> <p class="p1" ...

JavaScript code for sending information to the server

I am attempting to write data to a file on the server when a user clicks on a button, using JavaScript. I followed the method outlined in this Stack Overflow post: Saving a text file on server using JavaScript. Unfortunately, it did not work as expected. ...

Utilizing the power of JavaScript in an HTML file to develop a straightforward price calculator

I am new to the world of HTML coding and currently working on an assignment for my online computer course. I reached out to my professor for help, but unfortunately, he hasn't been very responsive. The task at hand is to create a basic cost calculator ...

Unable to trigger Vuejs click event when using v-if condition

I've encountered a strange issue. I'm attempting to trigger a method when an element is clicked in a v-for loop, but it doesn't seem to work when using v-if or v-show. Here's a sample of my HTML code: <div class="chosen-drop custom ...

My Vue component seems to be missing in my Vue.js project

Here is the code for my header.vue component: <template> <div> <h2>this is header h2</h2> </div> </template> <script> export default { name: 'Header', data () { return { dat ...

Sending a POST request in nodeJs that does not return any value

I have a button on my client site that sends a POST request to my server. The request does not require a response as it simply inserts data into the database. However, after clicking the button, the client continues to wait for a response until it times ou ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...

Compiling SCSS to CSS in Vue.js is a breeze

I am working on a vue js project that includes scss files. My goal is to compile these scss files into css and store them in the public folder. How can I achieve this? Should I make changes to the vue.config.js file? const path = require('path'); ...