Tips on preventing the mutation of v-model input in Vue

I have a code that calculates the amount of coins from an array. This code helps me determine how many items I can buy from a table with a given order. In the code, orderSize is being mutated in order to get the result. However, when I add an input field for manually entering the order size, the mutation causes the input text to change (if it is higher than the amount of the first item). I do not want the text to change. I have tried creating another variable that equals orderSize, but the same issue persists. How can I prevent the input text from being mutated? (Try entering any value higher than 100, and the text will change) (The array is coming from an outside source and I cannot control it) (If I do not mutate that variable, I will not be able to achieve my main goal of calculating the coin amount)

jsfiddle

new Vue({
  el: '#app',
  data: {
    orderSize : null,
  },
  computed: {
    calculateOrder () {
      var coinArray = [["100","1"],["200","2"],["300","3"],["400","4"], 
      ["500","5"],["600","6"]] ;
      var sum = 0
      var sum1 = 0
      var i= 0
      
      for (i = 0; i < coinArray.length; i++){
        if (coinArray[i][0]*coinArray[i][1] < this.orderSize) {
          sum1 += parseFloat(coinArray[i][1]);
          sum += coinArray[i][0]*coinArray[i][1];
          this.orderSize -= coinArray[i][0]*coinArray[i][1] ;        
        } else {
          return sum1+this.orderSize/parseFloat(coinArray[i][0]);
        }
      }
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
  <div id="app">
    <input v-model="orderSize" placeholder="Order $">
  <p>{{ calculateOrder }}</p>
</div>

Answer №1

It seems like the issue here lies in the fact that you are modifying the orderSize value with the -= operator, causing it to be reflected in the input field.

If you want to prevent this from happening, you should first create a new variable and copy the value of orderSize into it. Here's an example:

// Create a copy of the variable
let newSize = this.orderSize
for (...){
  if (...) {
    newSize -= coinArray[i][0]*coinArray[i][1];
  } else {
     return sum1+newSize/parseFloat(coinArray[i][0]);
  }

(I have omitted extraneous code and provided a simplified version for better understanding).

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

What is the best way to redirect a user to a different URL in Express while also sending additional data along with the request

[NODE, express] Developing a Facebook application where user grants access and is redirected to my site with a unique code at abc.com/heyBuddy/fb/callback?code="adasdasdasda". Once the code is received in route router.get('/heyBuddy/fb/callback', ...

Changing the location of an ArcGIS map with a click event in a Vue application

I am attempting to dynamically update a map to display my current location using Vue. I have created an onClick event that updates the props and sends them to my map component. To trigger a re-render of the map component when the data changes, I am utilizi ...

React.js - Add a new row div when reaching a limit of X items to keep the layout

Currently in the process of learning React.js. Here is the code snippet I am working with: const items = Object .keys(this.state.items) .map(key => <Item key={key} details={this.state.items[key]} />) ; return ( <div className ...

Issue with initializing Nuxt in GitHub Actions resulting in a critical error

I'm currently stuck on a Nuxt Fatal error while running a GitHub actions workflow for a nuxt app with cypress.js testing. Despite trying to decipher the stack trace, I can't seem to pinpoint the root cause of this issue during the app build. For ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

Is it possible to implement marker dragging in Google Maps v3 using JavaScript? How can this be achieved?

I am currently using this code to search for an address, drop a marker, and drag it afterwards. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title&g ...

What is the best method to transform URI data encoded in base64 into a file on the server side?

Looking for a solution to save a URI-data string as a jpg on the server using only Javascript. The alternative of writing it to a canvas and reading the image from there is not ideal. Any ideas? ...

Implementing phone verification code delivery using ReactJS and Twilio client: Step-by-step guide

I've been scouring the internet for the past 8 hours and haven't been able to find a tutorial on using Twilio to send SMS messages with ReactJS. Does anyone know of a good tutorial for this? ...

I am seeking assistance in transmitting data to my server utilizing Ajax, PHP, and mySQL without relying on a form

I have been researching tutorials on how to work with JavaScript without using forms. Currently, I have the JavaScript code that maps my answers based on clicks and generates an array shown in an alert. However, I am unsure if the Ajax request is sending i ...

nsIProcess - Launch with Background Execution and Deferred Activation

Currently, my method of launching Firefox is as follows: var exe = FileUtils.getFile('XREExeF', []); //this provides the path to the executable var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess); process.init ...

Generate an array in JavaScript using the values from input fields

Is there a way to create a JavaScript array that stores the values of all input fields with the class 'agency_field', when there are x number of these fields in the form? I attempted to achieve this using jQuery, but encountered a syntax error. ...

How can one locate the text coordinates within a div using JavaScript?

My current task involves locating the exact coordinates of the word "The" within this Wikipedia page once it has been displayed, similar to the coordinates provided by Chrome's developer tools. See a screenshot of developer options here. <div>Th ...

What is the best Document Object Model (DOM) to utilize alongside Spider

I want to incorporate the GoogleMaps JavaScript library into SpiderMonkey using the python wrapper, but the absence of a DOM is hindering my progress. Is there a method to inject a DOM into this setup in order to successfully make it function? ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

The error of "No 'Access-Control-Allow-Origin' header is present on the requested resource" persists even after implementing the Access-Control-Allow-Origin header

I'm trying to retrieve JSON data from a Firebase cloud function. The JSON URL works fine on the browser and my Android app, but I encounter issues when trying to fetch it in my JavaScript code. This results in an error message: No 'Access-Cont ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Polymer 1.0: Failure to update when binding CSS classes

Looking for some help with this code snippet: <dom-module id="foo-bar"> <template> <span class$="{{getState()}}">Foo Bar</span> </template> <script> (function() { class FooBar { ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

Managing and displaying information provided through forms

I'm currently developing a URL shortening tool, but I'm encountering difficulties in extracting jQuery form values to generate the shortened URL text. You can view the form layout here: <form name="urlForm"> <input type="text" name ...