Synchronize variables in a single Vue.js file

In my Vue file (version 2.x), I have three fields - input1 x input2 = result.

Whenever one of these fields is changed, the other two should update simultaneously. I attempted to use the watch property but it resulted in an infinite loop as the watchers kept triggering each other.

Is there a Vue helper that I am overlooking in this scenario? Any assistance would be greatly appreciated.

Please see the example code below:

<template>
  <input v-model="input1"></input>
  <input v-model="input2"></input>
  <input v-model="conversionRate"></input>
</template>

<script>
export default {
  data() {
    input1: null,
    input2: null,
    conversionRate: null
  },
  watch: {
    input1() {
      this.input2 = this.input1 * this.conversionRate
    },
    input2() {
      this.input1 = this.input2 * this.conversionRate
    },
    conversionRate() {
      this.input2 = this.input1 * this.conversionRate
    }
  }
}
</script>

Answer №1

Since the interdependence of all three models creates a never-ending cycle.

If you need to address this issue, consider utilizing the computed setter.

HTML

<div id="app">
  <input type="number" placeholder="amount" v-model="inputA"> X
  <input type="number" placeholder="rate" v-model="conversionRate"> =
  <input type="number" placeholder="total" v-model="total">
</div>

SCRIPT

new Vue({
  el: "#app",
  data: {
    total: 0,
    conversionRate: 1
  },
  computed: {
    inputA: {
      get() {
        return this.total / this.conversionRate;
      },
      set(newVal) {
        this.total = newVal * this.conversionRate;
      }
    }
  }
});

Check out the functional fiddle by visiting this link

Answer №2

Your observer on input2 is incorrect, causing an infinite loop (if the calculation involves floats, it's advisable to use Math.round). The correct code should be:

input2: function (newVal) {
   this.input1 = newVal / this.conversionRate // not newVal*this.conversionRate
}

However, @Vamsi Krishna may offer a better solution.

Here is a demo:

app = new Vue({
  el: "#app",
  data: function () {
    return {
      input1: null,
      input2: null,
      conversionRate: 1
    }
  },
  watch: {
    input1: function (newVal) {
      this.input2 = newVal * this.conversionRate
    },
    input2: function (newVal) {
      this.input1 = newVal / this.conversionRate
    },
    conversionRate: function (newVal) {
      this.input2 = this.input1 * newVal
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c5a59496c1e0219021d1a">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <input v-model="input1">
  <input v-model="input2">
  <input v-model="conversionRate">
</div>

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

Developing a dynamic slideshow using jQuery

I'm working on a website where I want an image to change when I click on a specific piece of text. Currently, I have set up a class called "device" with one of them having the class "active" like this: <div class="col-md-3"> <div c ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...

What is the process through which Generator.next() works with its parameter?

According to the documentation, it mentions that "You can also provide a parameter to the next method to send a value to the generator." But where exactly does it send this value to? Let's consider these 3 different generator functions: function* fi ...

JQuery event failed to trigger on the sorted row extraction using datatable.js

Utilizing DataTable.js to display data, I have <select> options in each <tr>. By default, DataTable only shows the first 10 rows with default parameters, and there's a JQ change event that is triggered for these initial rows. However, if t ...

Attempting to execute this function to verify the presence of matching email addresses within the database

function checkEmail(){ var email = $("#email").val(); var xmlhttp = new XMLHttpRequest(); var url = serverURL() + "/checkIfEmailExists.php"; url += "?email=" + email; xmlhttp.onreadystatechange=func ...

What is the best way to showcase data in a table using React Js?

I'm working on a project in React Js where I need to display data fetched from an API in a table. The challenge is that the data is received as an object and I'm struggling to map through it efficiently. Currently, I have hardcoded some sample da ...

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

Having trouble with updating links in HTML pages?

I'm having trouble updating all the links in my HTML file. The code I have isn't working as expected. var fs = require('fs'); fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){ if(!err){ html = ...

What is the best way to retrieve props from a component on my screen?

Hey everyone, I recently built a star rating component and successfully integrated it into my screen. Now, I'm trying to figure out how I can retrieve the value of the component in order to send it to the server upon submission. Here's a snippet ...

Steps for creating a Div element as a hyperlink without affecting the images it contains

Apologies for bringing up more queries regarding the same situation, but here it goes: Although my text is top-notch and images are perfectly placed, I am looking to prevent the jquery slide method from running when the images are clicked (as those clicks ...

Struggling to pass jasmine test when calling injected service

I've been grappling with unit testing in Angular and have hit a few obstacles along the way. While trying to set up a plnkr for my question regarding a failing Jasmine test that's making an $httpbackend call, I encountered a different error. It w ...

Favicon in browser blinks when hash changes

Whenever I adjust the hash location using either document.location.hash or window.location.hash, there seems to be a slight 'blinking' effect in most browsers. It's quite unattractive and I need to find a way to prevent it, especially since ...

Restrict user access to certain routes in Laravel and Vue to maintain security

I have constructed a single-page application using Laravel and Vue, and I am trying to restrict user access to the /products/create route. Despite my attempts with Laravel middlewares, I have not been successful in achieving this restriction. Below is an ...

Conceal the Bootstrap side navigation bar upon clicking anywhere else

Is there a way to make the side nav close when clicked outside of it while using my left side bar? Here is the code for my side nav: //side-nav is the class of my side nav //leftmenutrigger is my button on the nav bar that toggles the side nav Any sugg ...

Showing Div content from AngularJS response

Query -- I am currently using a Controller in AngularJs that performs an $http.get request and receives data as a response. The data includes an HTML DivID and corresponding classes. How can I extract this DivID from the response and transfer it to the vi ...

"Exploring the world of Angular 2 and the benefits of

Recently, I stumbled upon this git repository that discusses how developers can enhance scroll performance by incorporating 'passive listeners'. The first time I noticed it was when Chrome displayed warnings (specifically, "Handling of 'touc ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Retrieve a specific child element by clicking on a custom control on the map

I have a container element with three child spans. Using JQuery, I can determine which child was clicked when the container is clicked by utilizing the following function: $('.unitContainer').on('click','span',function(){ ...

Error occurred during JSON transmission to REST API - Access-Control-Allow-Origin restriction encountered

I am looking to send JSON data to my REST API. I have successfully tested it using Postman, but now I want to send data from my frontend. However, I am unsure about where to add the header and how to do it. My backend is built with Spring Boot and my front ...

Implementing Angular routing within the Express framework can enhance the user experience

I'm diving into Angular and Node/Express for the first time. I've successfully set up a node/express server and loaded the main index.jade file. However, I'm struggling to use Angular for routing between links on this page. The console consi ...