简体   繁体   中英

how to disable v-model input in Vue from mutating

I've a code for calculating coin amount from an array, this code allows me to learn how much i can buy from a table with given order, in code orderSize is mutating inorder to reach result but when i put an input area for manual entering ordersize that mutating causes input text to change(if it is higher than first item amount), i dont want text to change. I tried adding another variable that equals to orderSize but same thing happens. What should i do to prevent input text to be mutated. (Try entering any value higher than 100 text will change) (array is coming from outsource i cant control) (If i dont mutate that variable my main goal calculating coin amount cant be accomplished)

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> 

If I'm reading this correctly, the problem is that you are modifying orderSize by using -= , which will show up in the input.

If you want to avoid this, then first copy the value of orderSize to a new variable, eg:

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

(I have removed unrelated code, and contents of if / for for clarity).

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