vue开发环境实现登录
安装 Vue 开发环境
确保已安装 Node.js(建议版本 16+)和 npm/yarn。通过以下命令创建 Vue 项目:
npm create vue@latest my-vue-login
cd my-vue-login
npm install
配置路由和登录页面
安装 Vue Router 并配置路由:
npm install vue-router
在 src/router/index.js 中定义路由:
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
const routes = [
{ path: '/login', component: Login }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
创建登录组件
在 src/views/Login.vue 中实现登录表单:
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const username = ref('')
const password = ref('')
const router = useRouter()
const handleLogin = () => {
if (username.value && password.value) {
localStorage.setItem('isAuthenticated', 'true')
router.push('/')
}
}
</script>
状态管理与权限验证
使用 Pinia 或 Vuex 管理登录状态(以 Pinia 为例):
npm install pinia
在 src/stores/auth.js 中定义状态:
import { defineStore } from 'pinia'
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: localStorage.getItem('isAuthenticated') === 'true'
}),
actions: {
login() {
this.isAuthenticated = true
}
}
})
路由守卫配置
修改 src/router/index.js 添加全局守卫:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
if (to.path !== '/login' && !isAuthenticated) {
next('/login')
} else {
next()
}
})
后端接口对接(示例)
使用 Axios 发送登录请求:
npm install axios
在 Login.vue 中调用接口:
import axios from 'axios'
const handleLogin = async () => {
try {
const response = await axios.post('/api/login', {
username: username.value,
password: password.value
})
if (response.data.success) {
localStorage.setItem('token', response.data.token)
router.push('/')
}
} catch (error) {
console.error('登录失败', error)
}
}
环境变量配置
在项目根目录创建 .env 文件:
VITE_API_BASE_URL=http://your-api-url.com
通过 import.meta.env.VITE_API_BASE_URL 获取变量。
样式与优化
可引入 UI 库(如 Element Plus)优化表单样式:
npm install element-plus
在 main.js 中全局引入:
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)






