0๐
the console is executing different time because on top of your code you are using if statement if userId.length !=0 then on each key enter it will send request.please donโt use this if statement
0๐
- Button to send the request is a good idea, use that.(other
options could bekeyup
event, debounce if a button is too much). - Change the
v-if
to something more concrete like test for
user !== null
sinceuser
is default asnull
. - Check for a validation for a
number
input only when calling the
method from the button that makes sure that you intended the input to
be number and api is called only with a valid input.
Can try this:
<template>
<div>
<h2>Find User By ID</h2>
<input v-model="userId" type="number" placeholder="modifiez-moi" />
<!--@click is shorthand for v-on:click-->
<button @click="getUser($event)">Get User</button>
<br />
<p v-if="user !== null">
L'Utilisateur est : {{ displayWhateverHere }}
<br />
{{ user["id"] }} {{ user["email"] }} {{ user["username"] }}
</p>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "FindUser",
data() {
return {
user: null,
userId: ""
};
},
methods: {
getUser(event) {
/*Check for validations on input and then call the api*/
let validFlag = !isNaN(this.userId);
if (validFlag) {
axios
.get("http://localhost:4000/api/users/" + this.userId)
.then(response => {
console.log(response);
this.user = response.data.data;
/*If needed to clear the userId*/
this.userId = "";
});
} else {
/*input value is not a number -do something about it (alert/notify)*/
this.userId = "";
}
}
},
mounted() {
// this.getUser();
}
};
</script>
- [Vuejs]-Vue-test-utils not updating component after click
- [Vuejs]-How to update Vue component after it receives data
Source:stackexchange.com