想使用 Vue3 开发 web 页面的小伙伴,一步一步走起!
使用 Vue 3 开发一个简单的登录页面,让我们分成以下几个步骤:
1. 创建 Vue 3项目
首先,确保你已经安装了 Node.js 和 Vue CLI。如果还没有安装 Vue CLI,可以使用以下命令在终端下进行安装:
npm install -g @vue/cli
然后,创建一个新的 Vue 3 项目:
vue create MyVue3Web
在创建项目时,选择 Vue 3 作为项目的版本。
2. 创建登录组件
在 src/components 目录下创建一个新的组件文件 LoginForm.vue:
touch src/components/LoginForm.vue
或者其他终端命令,
vim src/components/LoginForm.vue
或者使用你已安装的 IDE 创建 LoginForm.vue 文件,例如,WebStorm
LoginForm.vue
3. 编写登录组件
在 LoginForm.vue 中编写登录表单的代码:
<input type="text" id="username" v-model="username" required /> <input type="password" id="password" v-model="password" required />登录
<script>
export default {
data() {
return {
username: '',
password: '',
};
},
methods: {
handleSubmit() {
// 在这里处理登录逻辑
if (this.username && this.password) {
alert(`用户名: ${this.username}, 密码: ${this.password}`);
// 你可以在这里调用 API 进行登录验证
} else {
alert('请输入用户名和密码');
}
},
},
};
</script>
.login-container {
max-width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
width: 100%;
padding: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
4. 在 App.vue 中使用登录组件
打开 src/App.vue 文件,将其中已有代码注释掉,并添加使用刚刚创建的 LoginForm 组件:
<script>
import LoginForm from './components/LoginForm.vue';
export default {
components: {
LoginForm,
},
};
</script>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
5. 运行项目
在终端命令行项目根目录下运行以下命令来启动开发服务器:
npm run serve
npm run serve
或者 WebStorm 内
npm run serve
然后,打开浏览器并访问 http://localhost:8080,你应该会看到一个简单的登录页面。
登录页面
6. 进一步扩展
- 表单验证:可以使用 Vue 的表单验证库(如 Vuelidate 或 VeeValidate)来增强表单验证功能。
- API 调用:可以在 handleSubmit 方法中调用后端 API 进行用户认证。
- 路由:可以使用 Vue Router 来实现登录后的页面跳转。
7. 部署
当你完成开发后,可以使用以下命令构建生产环境的代码:
npm run build
构建完成后,将 dist 目录下的文件部署到你的服务器上。
好了,这就是使用 Vue 3 开发一个简单登录页面的基本实现步骤。你可以根据需求进一步扩展和优化这个页面。
爱学习的小伙伴,关注不迷路哟~