I have two input fields, the idea is that both can change the value of the other one.
if a value of 1 - 200 is entered into the level field, Vue looks up the level and returns the amount of points for that level and enters them into the points field.
But I also want the inverse to happen, so if a user enters an amount of points they have in the points field Vue looks up the points and returns the level associated with that amount of points.
This works except Vue does a double calculation as it is watching both fields so if I enter 300 in the points field it correctly returns level 4 but then Vue detects the change in the level field and then changes the points to 250.
I only want Vue to detect when the user changes the field instead of re-calculating after it changes the field.
I hope this makes sense, it's a hard one to explain.
A sample of the data returned from the axios request:-
[
{"level":1,"points":0},
{"level":2,"points":72},
{"level":3,"points":175},
{"level":4,"points":250},
{"level":5,"points":401,}
]
a simplified vue component to demonstrate my working:-
<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>