Two input fields are available, where the value of one can affect the other.
If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them.
Conversely, if a user enters a specific amount of points in the points field, Vue will determine the associated level based on those points.
The current functionality works fine, but there's an issue with Vue performing double calculations because it's monitoring both fields. For example, entering 300 in the points field correctly returns level 4, but then it changes the points to 250 when it detects the change in the level field.
I'd like Vue to only trigger recalculations when the user actively changes a field, instead of reacting after each change.
Here's a snippet of data retrieved from an axios request:
[
{"level":1,"points":0},
{"level":2,"points":72},
{"level":3,"points":175},
{"level":4,"points":250},
{"level":5,"points":401,}
]
Below is a simplified Vue component illustrating the process:
<template>
<div>
<div class="card-body">
<form>
<div class="row">
<div class="col">
<div class="form-group">
<input type="text" v-model="currentLevel" class="form-control">
</div>
<div class="form-group">
<input type="text" v-model="currentPoints" class="form-control">
</div>
</div>
</div>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentLevel: 1,
currentPoints: 0,
pointsTable: []
}
},
mounted() {
axios.get('/api/points').then(this.fetchPointsTable);
},
methods: {
fetchPointsTable({data}) {
this.pointsTable = data;
}
},
watch: {
currentLevel: function() {
const result = this.pointsTable.find( ({ level }) => level === parseInt(this.currentLevel) );
this.currentPoints = result.experience;
},
currentPoints: function() {
var levels = [];
var goal = this.currentXp;
var closest = this.xpTable.reduce(function(prev, curr) {
if (curr.points <= goal) {
levels = curr.level;
}
return Math.max(levels);
});
this.currentLevel = closest;
}
}
}
</script>