如果你的代码是在Vue 组件中运行,可以按照以下步骤来实现账户查重功能。
- 在你的 Vue 组件中,添加一个输入框和一个按钮,并绑定对应的数据和方法
- 请确保你的后端接口 /api/checkAccount 能够接收到 account 参数并返回相应的结果。根据你的后端代码示例,你可能需要进行一些修改来适应 Vue 组件的请求。
<template>
<div>
<h1>账户查重</h1>
<input type="text" v-model="account" placeholder="请输入账号">
<button @click="checkAccount">检查账号</button>
<p>{{ resultText }}</p>
</div>
</template>
<script>
export default {
data() {
return {
account: '',
resultText: ''
};
},
methods: {
checkAccount() {
// 发送异步请求
fetch('http://localhost:9090/api/checkAccount?account=' + encodeURIComponent(this.account))
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.then(data => {
// 处理响应数据
if (data.code === 200) {
this.resultText = '账号可用';
} else if (data.code === 201) {
this.resultText = '账号已存在';
} else {
this.resultText = '验证失败,请重试';
}
})
.catch(error => {
console.error(error);
this.resultText = '请求失败,请重试';
});
}
}
};
</script>
以上代码示例是一个基本的 Vue 组件,将输入框的值绑定到 account 数据属性上,当点击按钮时,调用 checkAccount 方法发送异步请求。根据接口返回的结果,更新 resultText 属性,从而在页面上显示相应的提示信息。
实现效果如下: