[英]Passing a form value to build a Rest API url in Vue.js
I created this component in vue : 我在vue中创建了这个组件:
<template>
<div>
<h2>Find User By ID</h2>
<input v-model="userId" type="number" placeholder="modifiez-moi" />
<br />
<p v-if="userId.length != 0">
L'Utilisateur est : {{ getUser(userId) }}
<!-- returns nothing...-->
<br />
{{ user["id"] }} {{ user["email"] }} {{ user["username"]
}}<!-- returns object-->
</p>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "FindUser",
data() {
return {
user: null,
userId: ""
};
},
methods: {
getUser(userId) {
axios
.get("http://localhost:4000/api/users/" + this.userId)
.then(response => {
console.log(response);
this.user = response.data.data;
});
}
},
mounted() {
// this.getUser();
}
};
</script>
This code is working... But i have several issues : 这段代码正在工作...但是我有几个问题:
控制台执行的时间不同,因为在代码之上,您正在使用if语句if userId.length!= 0,然后在每个键上输入它将发送请求。请不要使用此if语句
keyup
event, debounce if a button is too much). keyup
事件,如果按钮太多,则反跳)。 v-if
to something more concrete like test for user !== null
since user
is default as null
. v-if
更改为更具体的内容,例如测试user !== null
因为默认情况下user
为null
。 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. number
输入的有效性,以确保您希望输入为数字,并且仅使用有效输入来调用api。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.