用Vue 写一个登录界面
时间: 2023-06-13 12:04:35 浏览: 66
Vue 是一个轻量级的 JavaScript 前端框架,可以方便地构建用户界面。下面是如何使用 Vue 写一个登录界面的示例:
1. 安装 Vue CLI:
```
npm install -g @vue/cli
```
2. 创建一个 Vue 项目:
```
vue create my-login-app
```
3. 在项目中安装一些必要的依赖:
```
cd my-login-app
npm install axios vuex --save
```
4. 在 `src` 目录下创建一个组件文件,例如 `Login.vue`:
```
<template>
<div>
<form>
<label for="username">用户名:</label>
<input id="username" v-model="username" type="text">
<label for="password">密码:</label>
<input id="password" v-model="password" type="password">
<button @click.prevent="submit">登录</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
import { mapActions } from 'vuex';
export default {
data() {
return {
username: '',
password: '',
};
},
methods: {
...mapActions(['login']),
async submit() {
try {
const response = await axios.post('/api/login', {
username: this.username,
password: this.password,
});
this.login({
token: response.data.token,
username: this.username,
});
} catch (error) {
console.error(error);
}
},
},
};
</script>
```
5. 在 `src/main.js` 文件中引入组件:
```
import Vue from 'vue';
import Login from './Login.vue';
new Vue({
el: '#app',
components: {
Login,
},
template: '<Login />',
});
```
6. 启动项目:
```
npm run serve
```
7. 在浏览器中访问 [http://localhost:8080](http://localhost:8080),您就可以看到