Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users can input the total and the amount = total / price will be computed accordingly. However, I am currently stuck at this stage:

var app = new Vue({
  el: '#app',
  data: {
    amount: 1,
    price: 100,
  },
  computed: {
    calcTotal: function() {
      return this.total =
        parseFloat(this.amount) *
        parseFloat(this.price)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  amount: <input v-model="amount"> <br><br> price: <input v-model="price" disabled> <br><br> total: <input v-model="calcTotal"> <br><br>

</div>

Answer №1

Instead of relying on the calculated property (calcTotal), you have the option to listen for the input-event from the <input> elements regarding the values of amount and total:

<input type="number" v-model="amount" @input="onAmountChange">
<input type="number" v-model="total" @input="onTotalChange">

The function associated with the amount input would update the value of total, and vice versa:

  data() {
    return {
      amount: 0,
      total: 0,
      price: 100,
    }
  },
  methods: {
    onTotalChange(e) {
      const total = e.currentTarget.value;
      this.amount = total / this.price;
    },
    onAmountChange(e) {
      const amount = e.currentTarget.value;
      this.total = amount * this.price;
    }
  }

new Vue({
  el: '#app',
  data() {
    return {
      amount: 0,
      total: 0,
      price: 100,
    }
  },
  methods: {
    onTotalChange(e) {
      const total = e.currentTarget.value;
      this.amount = total / this.price;
    },
    onAmountChange(e) {
      const amount = e.currentTarget.value;
      this.total = amount * this.price;
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6214170722504c574c5355">[email protected]</a>"></script>

<div id="app">
  <div>amount: <input type="number" v-model="amount" @input="onAmountChange"></div>
  <div>price: <input type="number" v-model="price" disabled></div>
  <div>total: <input type="number" v-model="total" @input="onTotalChange"></div>
</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

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

Validating a string with Hapi Joi validation for singles

Looking to perform basic validation on a single string, specifically the request header X-Value. Here's what I have tried. The issue I'm facing is that it always returns 'success' even when there is no X-Value header present. const ...

The error message "Blazor WebAssembly JSRuntime.InvokeVoidAsync - blazor.webassembly.js:1 Uncaught (in promise) TypeError: Converting circular structure to JSON" indicates that

I have implemented the drawio-integration project in my Blazor WebAssembly application. https://github.com/jgraph/drawio-integration This is how the simple helloworld sample appears: <img onclick='DiagramEditor.editElement(this);' src=" ...

What is the method to ensure an element is displayed in Selenium WebDriver?

Looking for assistance on how to choose options from a dropdown when the element is not visible and has a boolean attribute? Here's the HTML code snippet: <select id="visualizationId" style="width: 120px; display: none;" name="visualization"> & ...

How come my total isn't zero after I get a 1 on the dice roll?

I've been working on a dice game where if either of the dice rolls a 1, the score is set to 1. However, I'm having trouble getting that part of my code to work properly. I'm confident that everything else is functioning correctly. v ...

How can I run an ajax request in a loop where it only proceeds to the next loop value upon successful completion?

I'm facing a simple but important issue: running 3 Google Maps place URLs and displaying the results after each one is successful. Here's my current approach: var values = ["url1", "url2", "url3"]; values.forEach(function(value, i) { var ...

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

Choosing premier class and modifying characteristics

Looking for a solution to hide a div without modifying the HTML code directly? By using JQuery, you can manipulate the appearance of elements on a page. While it's possible to select the first instance of a class and retrieve its value, adding an attr ...

Transferring AJAX content to a Vue component

Presented below is a Vue component that renders passed props: <employee-times :employees="{{$employees}}" :supplies="{{$supplies}}" :commits="{{$commits}}" :times="{{$times}}"></employee-times> The template code includes filtering functionali ...

The Material-ui bug: multiple instances of the modal opening when a button is clicked

I have the following code in my render() method: render() { const classes = this.useStyles(); return ( <Paper style={classes.root}> <Table style={classes.table}> <TableBody> {this.state.deadTopics ...

Tips for including input text in a select option dropdown menu

Can someone guide me on adding an input text box to a select dropdown in Javascript and utilizing it as a search filter? <select class="form-control"> <option value="trans">Trans</option> <option value="fund">Fund</opt ...

What causes the discrepancy in CSS behavior between local and remote websites?

My chrome extension enhances facebook chatbox with jquery autocompletion. I am trying to make the suggestion list menu horizontal by modifying the jquery-ui.css. When changing display:block to display:inline, the list becomes horizontal in a local HTML fil ...

Initiate a unidirectional ajax request

My WCF service has a slow processing time when called for the first time, but caches the results in HttpRuntime.Cache afterwards. To initialize this cache, I want to initiate a fire-and-forget ajax call from JavaScript. Currently, my page contains the fol ...

Troubleshooting a Messaging Error between Background and Another Script

Attempting to transfer selected text from the current page to an HTML page using message passing: content script to background script, then background script to the HTML page. However, encountering errors if the HTML page is not already open, and even gett ...

Selenium Tips: Ensuring RemoteDriver Remains Connected to the Active Browser Tab

Currently working on a unique Windows application that utilizes voice commands to control web browsers. I am trying to figure out the best approach when users add tabs and modify the selected tab as needed. Unfortunately, RemoteDriver only supports swi ...

PHP Timer for Keeping Track of Time

Is it feasible to develop a timer using PHP that triggers an action after 60 seconds? I am looking for a countdown effect where the timer starts at 60 and decreases to 0. Ideally, I would like to refresh the corresponding div element to simulate the countd ...

Having issues getting Nunjucks templates to render correctly in Express

There seems to be an issue with setting up the template hierarchy in Express or possibly an error in how Nunjucks is being utilized. The goal is to have a template that includes common parts and specific pages that extend this template. It appears that the ...