用vue写一个带验证码的登录界面
时间: 2024-05-29 10:03:37 浏览: 32
好的,我可以为你提供一个简单的示例代码。
首先,你需要在你的Vue项目中安装 `vue-axios` 和 `vue-cookie` 库,用于发送请求和存储Cookie。
安装方式为:
```bash
npm install --save vue-axios vue-cookie
```
然后在你的Vue组件中,你可以编写如下的代码:
```vue
<template>
<div>
<form>
<div>
<label>用户名:</label>
<input type="text" v-model="username">
</div>
<div>
<label>密码:</label>
<input type="password" v-model="password">
</div>
<div>
<label>验证码:</label>
<input type="text" v-model="captcha">
<img :src="captchaUrl" @click="refreshCaptcha">
</div>
<button @click.prevent="login">登录</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
import VueAxios from 'vue-axios'
import VueCookie from 'vue-cookie'
export default {
name: 'LoginForm',
data() {
return {
username: '',
password: '',
captcha: '',
captchaUrl: '',
}
},
created() {
this.refreshCaptcha()
},
methods: {
login() {
const params = {
username: this.username,
password: this.password,
captcha: this.captcha,
}
this.$http.post('/api/login', params).then(response => {
if (response.data.code === 0) {
this.$cookie.set('token', response.data.token)
this.$router.push('/home')
} else {
this.$message.error(response.data.msg)
}
}).catch(error => {
console.error(error)
})
},
refreshCaptcha() {
this.captchaUrl = '/api/captcha?time=' + new Date().getTime()
},
},
mounted() {
Vue.use(VueAxios, axios)
Vue.use(VueCookie)
},
}
</script>
```
其中,`username`、`password` 和 `captcha` 分别绑定了输入框的值,`captchaUrl` 是验证码图片的URL地址。
在 `refreshCaptcha` 方法中,我们使用 `time` 参数来避免浏览器缓存,以确保每次刷新都能获取到新的验证码图片。
在 `login` 方法中,我们使用 `axios` 库向服务器发送POST请求,传递参数并获取响应结果。如果登录成功,我们使用 `vue-cookie` 库将服务器返回的 `token` 存储到浏览器的Cookie中,并跳转到主页。
你需要替换成你自己的接口地址,同时还需要在服务器端实现 `/api/login` 和 `/api/captcha` 接口,分别用于处理登录请求和获取验证码图片。