1. 为什么选择Vue3+NestJS全栈开发?
全栈开发已经成为现代Web开发的主流趋势,而Vue3和NestJS的组合正在成为企业级应用开发的热门选择。我最近完成了一个电商后台管理系统的开发,这套技术栈给我带来了不少惊喜。
Vue3作为前端框架,其Composition API彻底改变了组件开发方式。相比Vue2的Options API,它让逻辑组织更加灵活。在实际项目中,我特别喜欢用setup语法糖来组织代码,配合TypeScript的类型系统,开发体验直线上升。比如在处理复杂表单验证时,可以很自然地将验证逻辑抽离成独立的composable函数。
NestJS则是后端开发的利器。它基于TypeScript构建,采用了模块化的设计思想,内置依赖注入系统。我第一次用它开发RESTful API时,就被它的结构清晰度惊艳到了。控制器(Controller)、服务(Service)、模块(Module)的分层设计,让代码维护变得异常简单。特别是当项目规模扩大后,这种架构的优势更加明显。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 项目环境搭建与初始化
2.1 前端环境配置
首先确保你的系统已经安装了Node.js(建议16.x以上版本)。我推荐使用pnpm作为包管理器,它的安装速度和磁盘空间占用都比npm/yarn更优秀:
bash复制npm install -g pnpm
创建Vue3项目:
bash复制pnpm create vite@latest admin-frontend --template vue-ts
cd admin-frontend
pnpm install
关键依赖安装:
bash复制pnpm add vue-router@4 pinia@2 axios element-plus
这里我选择了Element Plus作为UI组件库,它在企业级后台系统中表现非常稳定。安装完成后,需要做一些基础配置:
- 在
src/main.ts中引入Element Plus:
typescript复制import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App)
.use(ElementPlus)
.mount('#app')
- 配置Vue Router,建议采用路由懒加载提升性能:
typescript复制const routes = [
{
path: '/login',
component: () => import('@/views/Login.vue')
},
// 其他路由...
]
2.2 后端环境配置
创建NestJS项目:
bash复制pnpm add -g @nestjs/cli
nest new admin-backend
cd admin-backend
pnpm install
NestJS项目初始化后会生成一个结构清晰的目录。我通常会立即安装这些开发依赖:
bash复制pnpm add -D prisma @prisma/client
pnpm add class-validator class-transformer @nestjs/config
数据库方面,我推荐使用Prisma作为ORM工具。它的类型安全特性和直观的数据模型定义方式,大大提升了开发效率。初始化Prisma:
bash复制npx prisma init
这会在项目根目录下生成prisma/schema.prisma文件,我们可以在这里定义数据模型。
3. 核心功能模块实现
3.1 用户认证系统
企业级后台的认证系统需要考虑安全性、可扩展性和易用性。我采用JWT(JSON Web Token)方案实现认证流程。
前端实现要点:
- 在Pinia中创建auth store管理登录状态:
typescript复制export const useAuthStore = defineStore('auth', {
state: () => ({
token: localStorage.getItem('token') || '',
userInfo: null
}),
actions: {
async login(credentials) {
const { data } = await axios.post('/auth/login', credentials)
this.token = data.token
localStorage.setItem('token', data.token)
axios.defaults.headers.common['Authorization'] = `Bearer ${data.token}`
},
// 其他方法...
}
})
- 实现路由守卫:
typescript复制router.beforeEach((to) => {
const authStore = useAuthStore()
if (to.meta.requiresAuth && !authStore.token) {
return '/login'
}
})
后端实现要点:
- 创建Auth模块:
bash复制nest g module auth
nest g service auth
nest g controller auth
- 实现JWT策略(使用
@nestjs/passport):
typescript复制@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET')
})
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username }
}
}
- 登录接口实现:
typescript复制@Post('login')
async login(@Body() loginDto: LoginDto) {
const user = await this.auth
