vue3移动端架构
🌐 Modern Vue 3 Frontend Architecture (Using Yarn)
本架构适用于基于 Vite 构建的 Vue 3 前端项目,使用 Yarn 作为包管理工具,结合自动导入、自动组件注册、状态管理、路由、API 拦截、样式体系与代码规范,实现高性能与可维护性的现代化开发流程。
🧩 目录结构
1 | my-vue-app/ |
⏳ 开发思路与生命周期
- 构建阶段:使用 Vite + Yarn 快速创建项目与安装依赖。
- 运行时初始化:
main.ts
中创建 Vue 应用,注入 Pinia、Router、Tailwind、Axios 等模块。 - 组件结构组织:
hooks/
、components/
、store/
、views/
、api/
等分区构成清晰的模块划分。 - 路由管理:采用 Vue Router 4 实现懒加载与权限校验(Navigation Guards)。
- 状态管理:使用 Pinia + 持久化插件管理全局状态。
- API 通信:创建 Axios 实例,在
api/
中统一编写接口调用。 - 样式体系:Tailwind CSS 实现原子化样式,集中管理设计变量。
- 开发规范:配置 ESLint、Prettier、Stylelint,结合 Husky 与 lint-staged 实现提交前自动检查。
🔧 手把手搭建步骤(Yarn 版)
1. 初始化项目
1 | yarn create vite my-vue-app --template vue-ts |
Yarn 的
create vite
命令能快速创建 Vue 项目,支持框架选择和模板配置 (classic.yarnpkg.com, vuejs.org)。
2. 安装依赖
1 | yarn |
3. 配置 Vite 插件
在 vite.config.ts
中配置自动导入与组件注册:
1 | import { defineConfig } from 'vite' |
4. 初始化 Tailwind
1 | npx tailwindcss init -p |
配置 tailwind.config.js
:
1 | module.exports = { |
5. 修改主入口 main.ts
1 | import { createApp } from 'vue' |
6. 补充目录代码
Router (
src/router/index.ts
):1
2
3
4
5import Home from '@/views/Home.vue'
export default [
{ path: '/', component: Home },
{ path: '/about', component: () => import('@/views/About.vue') },
]Store (
src/store/user.ts
):1
2
3
4
5
6import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({ token: '' }),
persist: true,
actions: { setToken(t: string) { this.token = t } },
})API (
src/api/index.ts
):1
2
3
4
5
6
7
8
9
10
11import axios from 'axios'
export const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 10000,
})
api.interceptors.request.use(cfg => {
const t = localStorage.getItem('token')
if (t) cfg.headers.Authorization = `Bearer ${t}`
return cfg
})
api.interceptors.response.use(res => res.data, err => Promise.reject(err))
7. 设置代码规范与提交检查
1 | npx husky-init && yarn |
在 package.json
中加入:
1 | "lint-staged": { |
完成后每次提交时自动格式化代码。
8. 启动开发
执行:
1 | yarn dev |
访问 http://localhost:5173,自动导入、组件注册、状态持久、API 拦截、样式系统均已生效。
✅ 总结
- Yarn 提供快速依赖安装与缓存能力,是项目推荐选择。
- Vue 官方支持
yarn create vue
和yarn create vite
初始化。 - 提供完整生产与开发流程:从初始化、代码组织、模块注册、规范检测到项目启动。
- 完整生命周期覆盖构建→开发→提交保护。
可以复制本模块作为项目模板,或生成 README 与部署脚本。如有其它需求,欢迎继续交流!
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.