
这份笔记不是单纯的“装几个库”。它从代码规范开始,一直写到 Vue3 + TypeScript 后台 CMS 的组件抽离、动态路由、权限按钮、Axios 封装、表单双向绑定和请求竞态处理。 TL;DR: 先用 EditorConfig、Pr
这份笔记不是单纯的“装几个库”。它从代码规范开始,一直写到 Vue3 + TypeScript 后台 CMS 的组件抽离、动态路由、权限按钮、Axios 封装、表单双向绑定和请求竞态处理。
**TL;DR:**先用 EditorConfig、Prettier、ESLint、Husky、Commitizen、commitlint 固定团队写法,再接入 vue-router、Vuex、Element Plus、Axios。项目结构上采用 view 页面层、components 公共组件层、base-ui 基础组件层。后台权限通过后端菜单生成动态路由和按钮权限。网络层用封装的请求类和拦截器处理 token、loading、响应数据和错误。
适合准备搭建 Vue3 + TypeScript 后台项目,或接手类似 CMS 项目的人。你应该已经会 Vue3 基础语法,并能看懂 TypeScript 类型、Vue Router、Vuex 和 Element Plus 示例。
源笔记的顺序很实用,可以分成五层:
| 层级 | 目标 | 源笔记内容 |
|---|---|---|
| 代码规范 | 让团队输出一致 | EditorConfig、Prettier、ESLint、Husky、Commitizen、commitlint |
| 基础能力 | 路由、状态、UI、请求 | vue-router、Vuex、Element Plus、Axios |
| 组件架构 | 降低页面重复 | base-ui、components、views 三层 |
| 权限模型 | 菜单和按钮按用户权限生成 | 后端菜单映射路由、按钮权限数组、动态注册 |
| 工程细节 | 表单绑定、插槽、请求竞态 | v-model、动态插槽、缓存、取消重复请求 |
EditorConfig 负责跨编辑器统一基础格式:
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
Prettier 负责格式化代码。源笔记配置为 2 空格、单引号、无分号:
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
ESLint 负责代码质量检查。源笔记通过 eslint-plugin-prettier 和 eslint-config-prettier 处理 ESLint 与 Prettier 的冲突:
npm i eslint-plugin-prettier eslint-config-prettier -D
Husky 把检查放进 Git 提交流程:
npx husky-init && npm install
Commitizen 和 commitlint 解决提交信息风格:
npm install commitizen -D
npx commitizen init cz-conventional-changelog --save-dev --save-exact
npm i @commitlint/config-conventional @commitlint/cli -D
这部分的目标不是追求工具数量,而是把“格式、lint、提交信息”变成自动检查。
源笔记列了三种配置方式:
publicPath、outputDir。configureWebpack 合并或修改 webpack 配置。chainWebpack 使用 webpack-chain 修改配置。示例:
const path = require("path");
module.exports = {
outputDir: "./build",
chainWebpack: (config) => {
config.resolve.alias
.set("@", path.resolve(__dirname, "src"))
.set("views", "@/views");
}
};
源笔记使用 vue-router@next:
import { createRouter, createWebHashHistory } from "vue-router";
import { RouteRecordRaw } from "vue-router";
const routes: RouteRecordRaw[] = [
{
path: "/",
redirect: "/main"
},
{
path: "/main",
component: () => import("../views/main/main.vue")
},
{
path: "/login",
component: () => import("../views/login/login.vue")
}
];
const router = createRouter({
routes,
history: createWebHashHistory()
});
export default router;
入口安装:
import router from "./router";
createApp(App).use(router).mount("#app");
Vuex 创建 store:
import { createStore } from "vuex";
const store = createStore({
state() {
return {
name: "coderwhy"
};
}
});
export default store;
Element Plus 可以全局引入,也可以局部引入。源笔记还写了一个 register-element.ts,把常用组件集中注册:
import "element-plus/dist/index.css";
import { App } from "vue";
import {
ElAlert,
ElAside,
ElButton,
ElForm,
ElFormItem,
ElInput,
ElRadio
} from "element-plus";
const components = [
ElAlert,
ElAside,
ElButton,
ElForm,
ElFormItem,
ElInput,
ElRadio
];
export default function (app: App): void {
for (const component of components) {
app.component(component.name, component);
}
}
这种做法适合后台项目,因为基础 UI 组件会在很多页面重复出现。
源笔记先给出基础 Axios 类,再在后面扩展成多层封装。核心目标是:
Authorization。简化后的结构:
class YCRequest {
private instance: AxiosInstance;
private interceptors?: YCRequestInterceptors;
private showLoading: boolean;
constructor(config: YCRequestConfig) {
this.instance = axios.create(config);
this.showLoading = config.showLoading ?? true;
this.interceptors = config.interceptors;
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptor,
this.interceptors?.requestInterceptorCatch
);
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCatch
);
}
request<T = any>(config: YCRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
if (config.interceptors?.requestInterceptor) {
config = config.interceptors.requestInterceptor(config);
}
this.instance
.request<any, T>(config)
.then((res) => {
if (config.interceptors?.responseInterceptor) {
res = config.interceptors.responseInterceptor(res);
}
resolve(res);
})
.catch((err) => {
reject(err);
});
});
}
}
应用 API 层再基于请求实例封装具体接口:
enum LoginAPI {
AccountLogin = "/login",
LoginUserInfo = "/users/",
UserMenus = "/role/"
}
export function accountLoginRequest(account: IAccount) {
return ycRequest.post<IDataType<IloginResult>>({
url: LoginAPI.AccountLogin,
data: account
});
}
源笔记把后台 CMS 组件抽离成三层:
view 页面层 -> components 公共组件层 -> base-ui 基础组件层
base-ui 是最抽象的基础组件。例如表单组件根据 formItems 配置渲染 input、password、select、datepicker,并用 modelValue[item.field] 读值,用 update:modelValue 回传新对象。
<el-input
v-bind="item.otherOptions"
:placeholder="item.placeholder"
:show-password="item.type === 'password'"
:model-value="modelValue[`${item.field}`]"
@update:modelValue="handleValueChange($event, item.field)"
/>
const handleValueChange = (value: any, field: string) => {
emit("update:modelValue", { ...props.modelValue, [field]: value });
};
对应类型:
type IFormType = "input" | "password" | "select" | "datepicker";
export interface IFormItem {
field: string;
type: IFormType;
label: string;
rules?: any[];
placeholder?: any;
options?: any[];
otherOptions?: any;
isHidden?: boolean;
}
components 层封装业务公共组件。例如 PageContent 接收表格配置,内部处理分页、数据请求、按钮权限、固定插槽和动态插槽。
views 层只负责组合页面:
<PageSearch
:searchFormConfig="searchFormConfig"
@resetBtnClick="handleResetClick"
@queryBtnClick="handleQueryClick"
/>
<PageContent
ref="pageContentRef"
:contentTableConfig="contentTableConfig"
pageName="users"
@newBtnClick="handleNewData"
@editBtnClick="handleEditData"
/>
<PageModal
ref="pageModalRef"
:defaultInfo="defaultInfo"
:modalConfig="modalConfigRef"
pageName="users"
/>
这样做的收益是:新增页面时主要写配置文件,而不是复制大量组件模板。
源笔记中的 content.config.ts 用配置描述用户列表:
export const contentTableConfig = {
title: "用户列表",
propList: [
{ prop: "name", label: "用户名", minWidth: "100" },
{ prop: "realname", label: "真实姓名", minWidth: "100" },
{ prop: "cellphone", label: "手机号码", minWidth: "100" },
{
prop: "enable",
label: "状态",
minWidth: "100",
slotName: "status"
},
{
label: "操作",
minWidth: "120",
slotName: "handler"
}
],
showIndexColumn: true,
showSelectColumn: true
};
页面里再用 hook 把搜索、重置、新增、编辑抽出来:
const [pageContentRef, handleQueryClick, handleResetClick] = usePageSearch();
const [pageModalRef, defaultInfo, handleNewData, handleEditData] =
usePageModal(newCallback, editCallback);
这类配置驱动适合后台系统。它的代价是类型设计和插槽协议要稳定,否则配置会变成另一种隐式代码。
源笔记比较了三种路由方案:
第三种是源笔记采用的方案。
动态路由核心函数会先加载所有本地路由文件,再递归后端菜单,找到 type 为 2 且路径匹配的菜单,加入可访问路由:
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
const routes: RouteRecordRaw[] = [];
const allRoutes: RouteRecordRaw[] = [];
const routeFiles = require.context("../router/main", true, /\.ts/);
routeFiles.keys().forEach((key) => {
const route = require("../router/main" + key.split(".")[1]);
allRoutes.push(route.default);
});
const recurseGetRoute = (menus: any[]) => {
for (const menu of menus) {
if (menu.type === 2) {
const route = allRoutes.find((route) => route.path === menu.url);
if (route) routes.push(route);
} else {
recurseGetRoute(menu.children);
}
}
};
recurseGetRoute(userMenus);
return routes;
}
登录后,Vuex 请求用户信息和用户菜单,提交菜单时动态注册路由:
const routes = mapMenusToRoutes(userMenus);
routes.forEach((route) => {
router.addRoute("main", route);
});
const permissions = mapMenusToPermissions(userMenus);
state.permissions = permissions;
按钮权限通过菜单里的 type 3 permission 收集成数组,再由 hook 判断当前页面是否有 create、update、delete、query 权限。
源笔记记录了父子表单双向绑定的多个方案。更清晰的做法是子组件用 modelValue 接收值,用 update:modelValue 通知父组件。
对于对象表单,源笔记最后使用了本地 ref 拷贝,再 deep watch 回传:
const formData = ref({ ...props.modelValue });
watch(
formData,
(newValue) => {
emit("update:modelValue", newValue);
},
{
deep: true
}
);
这个方案能工作,但要清楚它的边界:父组件后续主动替换 modelValue 时,还需要考虑本地副本如何同步。
源笔记最后记录了分页、搜索、选项卡等场景的竞态问题:先发出的请求不一定先返回,旧响应可能覆盖新状态。
解决思路是发出新请求时取消上一次相同请求。源笔记先介绍 Axios CancelToken,也记录了 v0.22.0 后 Axios 支持 AbortController。
const controller = new AbortController();
axios.get("/xxx", {
signal: controller.signal
});
controller.abort();
源笔记的业务实现还加入了前端缓存、pending 队列、请求拦截、响应拦截、token、过期时间和取消判断。这个方向适合请求频繁的列表页,但需要认真处理错误分支,避免把取消请求当成普通失败提示给用户。
本文没有逐行复写源笔记里的全部 VSCode 配置、EChart 封装、动态插槽图片和完整 Axios 类。它保留项目初始化和 CMS 架构主线。
源笔记使用 Vue CLI、Vuex、Element Plus、Axios、webpack 相关写法。本文不判断这些依赖在新项目中是否仍是最佳选择,只按源文件语境整理。
建议按这个顺序落地:
今日AI领域节奏平缓,DeepSeek V4.1 Flash、MiniMax M3.1 Flash和Mercury 3三款新模型亮相,但短期难以大规模落地。Vercel AI SDK与LangChain.js持续迭代,新增推理参数并完善网关路由。纽约市长呼吁加强AI监管。
OpenAI为GPT-6.2 Astra与Sol强化推理防提取,红队提取成功率从54%降至0.2%,并每周处置数千至数万账号打击协同蒸馏。这提示开发者API行为或更保守,企业需重估蒸馏与微调合规风险,模型能力开放与知识产权保护张力上升。
Codex 好不好用,关键不在提示词,而在工作方式。本文整理 10 条实战技巧:侧边聊与主会话分工、多 Agent 并行、按任务选模型、讨论落成 Spec、按根因批量修 Bug、七成时间做规划、续接旧会话、用 Skill 固化 SOP、多 Agent 交叉审查,以及让 AI 说大白话。
新内容发布后发送确认邮件,不会把未验证或已退订地址加入发送列表。
欢迎理性讨论与补充勘误
无需登录即可评论,展示名称会使用脱敏 IP。
暂无评论