vue管理系统项目实现
Vue 管理系统项目实现指南
项目初始化
使用 Vue CLI 或 Vite 创建项目,推荐 Vue 3 + TypeScript 模板。安装依赖如 vue-router、pinia、axios 和 UI 库(Element Plus/Ant Design Vue)。
npm create vue@latest vue-admin
cd vue-admin
npm install vue-router pinia axios element-plus
路由配置
在 src/router/index.ts 中配置动态路由,结合权限控制。使用懒加载提升性能。
const routes = [
{
path: '/',
component: () => import('@/layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('@/views/Dashboard.vue') },
{ path: 'users', component: () => import('@/views/UserList.vue') }
]
}
]
状态管理
采用 Pinia 管理全局状态,例如用户信息和权限数据。创建 stores/user.ts:
export const useUserStore = defineStore('user', {
state: () => ({
token: '',
roles: []
}),
actions: {
async login(formData) {
const res = await api.login(formData)
this.token = res.token
}
}
})
API 封装
在 src/api 目录下封装 axios 实例,统一处理请求拦截和响应错误。
const service = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 5000
})
service.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${userStore.token}`
return config
})
权限控制
实现路由守卫,在 router.beforeEach 中校验用户权限,动态加载可访问路由。
router.beforeEach(async (to) => {
const userStore = useUserStore()
if (!userStore.token && to.path !== '/login') {
return '/login'
}
})
组件开发
按功能模块划分组件,如 src/components/TableSearch 封装搜索表单。使用 Composition API 组织逻辑。
<script setup>
const searchForm = reactive({
keyword: '',
status: ''
})
</script>
<template>
<el-form :model="searchForm">
<el-input v-model="searchForm.keyword" />
</el-form>
</template>
样式管理
采用 SCSS 预处理器,在 src/assets/styles 中定义变量和混合。使用 CSS 变量实现主题切换。
:root {
--primary-color: #409eff;
}
.dark {
--primary-color: #3375b9;
}
构建优化
配置 vite.config.ts 进行代码分割和压缩。使用插件自动生成 SVG 图标组件。
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
'element-plus': ['element-plus']
}
}
}
}
})
部署发布
配置 Nginx 生产环境,启用 gzip 压缩。设置反向代理解决跨域问题。
server {
gzip on;
location /api {
proxy_pass http://backend;
}
}
调试工具
集成 Vue DevTools 和 ESLint + Prettier 保证代码规范。使用 Mock.js 模拟接口数据开发。
Mock.mock('/api/users', {
'list|10': [{ id: '@id', name: '@cname' }]
})






