Loading...
Loading...
Compare original and translation side by side
<script setup><script setup>.vue.vuesrc/
├── api/ # API client and endpoint definitions
├── assets/ # Static assets (images, fonts, icons)
├── components/ # Shared/reusable components
│ ├── base/ # Base UI primitives (Button, Input, Modal)
│ └── features/ # Feature-specific shared components
├── composables/ # Reusable Composition API logic
├── layouts/ # Page layouts (optional)
├── pages/ # Route-level page components
├── router/ # Vue Router configuration
├── stores/ # Pinia stores
├── types/ # TypeScript type definitions
├── utils/ # Pure utility functions
└── App.vue # Root componentsrc/
├── api/ # API 客户端与端点定义
├── assets/ # 静态资源(图片、字体、图标)
├── components/ # 共享/可复用组件
│ ├── base/ # 基础 UI 原语(Button、Input、Modal)
│ └── features/ # 功能专属的共享组件
├── composables/ # 可复用的 Composition API 逻辑
├── layouts/ # 页面布局(可选)
├── pages/ # 路由级页面组件
├── router/ # Vue Router 配置
├── stores/ # Pinia 状态仓库
├── types/ # TypeScript 类型定义
├── utils/ # 纯工具函数
└── App.vue # 根组件| Convention | When to Use |
|---|---|
| All components (enforced by |
| Composables |
| Utilities, API clients, types |
| Route segments, feature folders |
| 命名规则 | 使用场景 |
|---|---|
| 所有组件(由 |
| 组合式函数 |
| 工具函数、API 客户端、类型定义 |
| 路由片段、功能文件夹 |
<script setup lang="ts">
// 1. Imports (vue → ecosystem → absolute → relative)
// 2. Props & Emits & Slots
// 3. Composables
// 4. Local state (ref/reactive)
// 5. Computed properties
// 6. Methods
// 7. Watchers
// 8. Lifecycle hooks
</script>
<template>
<!-- Template content -->
</template>
<style scoped>
/* Scoped styles */
</style><script setup lang="ts">
// 1. 导入(vue → 生态库 → 绝对路径 → 相对路径)
// 2. Props & Emits & Slots
// 3. 组合式函数
// 4. 本地状态(ref/reactive)
// 5. 计算属性
// 6. 方法
// 7. 监听器
// 8. 生命周期钩子
</script>
<template>
<!-- 模板内容 -->
</template>
<style scoped>
/* 作用域样式 */
</style>// Type-based props with defaults
interface Props {
label: string;
variant?: "primary" | "secondary";
disabled?: boolean;
items: Item[];
}
const props = withDefaults(defineProps<Props>(), {
variant: "primary",
disabled: false,
});typerequireddefaultisXxxhasXxxcanXxxdefineModel()modelValueupdate:modelValue// 基于类型的 Props 与默认值
interface Props {
label: string;
variant?: "primary" | "secondary";
disabled?: boolean;
items: Item[];
}
const props = withDefaults(defineProps<Props>(), {
variant: "primary",
disabled: false,
});typerequireddefaultisXxxhasXxxcanXxxdefineModel()modelValueupdate:modelValueconst emit = defineEmits<{
submit: [];
"update:modelValue": [value: string];
select: [id: string, index: number];
}>();@update:model-valueemit("update:modelValue", val)const emit = defineEmits<{
submit: [];
"update:modelValue": [value: string];
select: [id: string, index: number];
}>();@update:model-valueemit("update:modelValue", val)// composables/useDebounce.ts
export function useDebounce<T>(value: MaybeRef<T>, delay: number): Ref<T> {
const debounced = ref(toValue(value)) as Ref<T>;
let timer: ReturnType<typeof setTimeout>;
watch(
() => toValue(value),
(newVal) => {
clearTimeout(timer);
timer = setTimeout(() => { debounced.value = newVal; }, delay);
}
);
onUnmounted(() => clearTimeout(timer));
return readonly(debounced);
}// composables/useDebounce.ts
export function useDebounce<T>(value: MaybeRef<T>, delay: number): Ref<T> {
const debounced = ref(toValue(value)) as Ref<T>;
let timer: ReturnType<typeof setTimeout>;
watch(
() => toValue(value),
(newVal) => {
clearTimeout(timer);
timer = setTimeout(() => { debounced.value = newVal; }, delay);
}
);
onUnmounted(() => clearTimeout(timer));
return readonly(debounced);
}userefcomputedreactiveMaybeReftoRef()toValue()onUnmountedonCleanupuserefcomputedreactiveMaybeReftoRef()toValue()onUnmountedonCleanup| Pattern | Use Case |
|---|---|
| Local component state |
| Props + Emits | Parent-child communication |
| Provide / Inject | Theme, config, plugin API |
| Pinia store | Global, shared, complex state |
| Server state composable | API data with caching (wrap |
| 模式 | 使用场景 |
|---|---|
| 组件本地状态 |
| Props + Emits | 父子组件通信 |
| Provide / Inject | 主题、配置、插件 API |
| Pinia 状态仓库 | 全局共享的复杂状态 |
| 服务端状态组合式函数 | 带缓存的 API 数据(封装 |
// stores/useCartStore.ts
export const useCartStore = defineStore("cart", () => {
const items = ref<CartItem[]>([]);
const isLoading = ref(false);
const totalPrice = computed(() =>
items.value.reduce((sum, i) => sum + i.price * i.quantity, 0)
);
const itemCount = computed(() =>
items.value.reduce((sum, i) => sum + i.quantity, 0)
);
async function addItem(productId: string) {
isLoading.value = true;
try {
const item = await fetchProduct(productId);
const existing = items.value.find(i => i.id === item.id);
if (existing) existing.quantity++;
else items.value.push({ ...item, quantity: 1 });
} finally {
isLoading.value = false;
}
}
return { items, isLoading, totalPrice, itemCount, addItem };
});$patch()// stores/useCartStore.ts
export const useCartStore = defineStore("cart", () => {
const items = ref<CartItem[]>([]);
const isLoading = ref(false);
const totalPrice = computed(() =>
items.value.reduce((sum, i) => sum + i.price * i.quantity, 0)
);
const itemCount = computed(() =>
items.value.reduce((sum, i) => sum + i.quantity, 0)
);
async function addItem(productId: string) {
isLoading.value = true;
try {
const item = await fetchProduct(productId);
const existing = items.value.find(i => i.id === item.id);
if (existing) existing.quantity++;
else items.value.push({ ...item, quantity: 1 });
} finally {
isLoading.value = false;
}
}
return { items, isLoading, totalPrice, itemCount, addItem };
});$patch()const routes = [
{
path: "/users/:id",
name: "user-detail",
component: () => import("@/pages/UserDetail.vue"), // lazy
props: true, // pass params as props
meta: { requiresAuth: true },
},
];const routes = [
{
path: "/users/:id",
name: "user-detail",
component: () => import("@/pages/UserDetail.vue"), // 懒加载
props: true, // 将路由参数作为 props 传递
meta: { requiresAuth: true },
},
];router.beforeEach((to, from) => {
const { isLoggedIn } = useAuthStore();
if (to.meta.requiresAuth && !isLoggedIn) {
return { name: "login", query: { redirect: to.fullPath } };
}
});router.beforeEach((to, from) => {
const { isLoggedIn } = useAuthStore();
if (to.meta.requiresAuth && !isLoggedIn) {
return { name: "login", query: { redirect: to.fullPath } };
}
});const route = useRoute();
const id = computed(() => route.params.id as string);
watch(id, (newId) => fetchItem(newId));const route = useRoute();
const id = computed(() => route.params.id as string);
watch(id, (newId) => fetchItem(newId));<!-- v-if/v-else-if/v-else -->
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<div v-else>{{ content }}</div>
<!-- v-show for frequent toggles -->
<div v-show="isOpen">Toggled content</div>
<!-- v-for with stable keys -->
<div v-for="item in items" :key="item.id">{{ item.name }}</div>
<!-- Computed filtered list (not v-if + v-for on same element) -->
<div v-for="item in activeItems" :key="item.id">{{ item.name }}</div>
<!-- Event handling -->
<form @submit.prevent="handleSubmit">
<button type="submit">Save</button>
</form>
<!-- v-model -->
<input v-model="name" />
<CustomInput v-model="value" v-model:title="title" /><!-- v-if/v-else-if/v-else -->
<div v-if="isLoading">加载中...</div>
<div v-else-if="error">错误:{{ error }}</div>
<div v-else>{{ content }}</div>
<!-- 频繁切换使用 v-show -->
<div v-show="isOpen">可切换内容</div>
<!-- v-for 使用稳定 key -->
<div v-for="item in items" :key="item.id">{{ item.name }}</div>
<!-- 使用计算属性过滤列表(避免同一元素上同时使用 v-if + v-for) -->
<div v-for="item in activeItems" :key="item.id">{{ item.name }}</div>
<!-- 事件处理 -->
<form @submit.prevent="handleSubmit">
<button type="submit">保存</button>
</form>
<!-- v-model 双向绑定 -->
<input v-model="name" />
<CustomInput v-model="value" v-model:title="title" />| Technique | When to Use |
|---|---|
| List items that rarely change |
| Content rendered once and static forever |
| Large data structures replaced wholesale |
| Only top-level properties are reactive |
| Frequent visibility toggles |
| Cache toggled views |
| Lazy routes | |
| Async component loading with fallback |
| 技巧 | 使用场景 |
|---|---|
| 极少变化的列表项 |
| 仅渲染一次且永久静态的内容 |
| 整体替换的大型数据结构 |
| 仅需顶层属性响应式的对象 |
优先使用 | 频繁切换可见性的元素 |
| 缓存切换的视图 |
| 路由懒加载 | 非核心路由使用 |
| 异步组件加载时显示 fallback 内容 |
import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import UserCard from "./UserCard.vue";
beforeEach(() => { setActivePinia(createPinia()); });
it("renders and emits", async () => {
const wrapper = mount(UserCard, {
props: { user: { id: "1", name: "Alice" } },
});
expect(wrapper.text()).toContain("Alice");
await wrapper.find("button").trigger("click");
expect(wrapper.emitted("select")![0]).toEqual(["1"]);
});import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import UserCard from "./UserCard.vue";
beforeEach(() => { setActivePinia(createPinia()); });
it("渲染并触发事件", async () => {
const wrapper = mount(UserCard, {
props: { user: { id: "1", name: "Alice" } },
});
expect(wrapper.text()).toContain("Alice");
await wrapper.find("button").trigger("click");
expect(wrapper.emitted("select")![0]).toEqual(["1"]);
});refcomputedwatchuseFetchuseAsyncDatarefcomputedwatchuseFetchuseAsyncDataconst { data: user, pending, error, refresh } = await useAsyncData(
"user", // unique key for caching
() => $fetch(`/api/users/${id}`),
);
const { data: posts } = await useFetch("/api/posts", {
query: { page: 1 },
key: "posts-page-1", // dedupes requests
});const { data: user, pending, error, refresh } = await useAsyncData(
"user", // 缓存唯一标识
() => $fetch(`/api/users/${id}`),
);
const { data: posts } = await useFetch("/api/posts", {
query: { page: 1 },
key: "posts-page-1", // 避免重复请求
});// server/api/users/[id].ts
export default defineEventHandler(async (event) => {
const { id } = await getValidatedRouterParams(event, z.object({
id: z.string().uuid(),
}).parse);
// ... fetch and return
});// server/api/users/[id].ts
export default defineEventHandler(async (event) => {
const { id } = await getValidatedRouterParams(event, z.object({
id: z.string().uuid(),
}).parse);
// ... 获取数据并返回
});// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// server-only
apiSecret: "",
// public (exposed to client)
public: {
apiBase: "https://api.example.com",
},
},
});// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// 仅服务端可见
apiSecret: "",
// 客户端可见(暴露给前端)
public: {
apiBase: "https://api.example.com",
},
},
});defineProps()// Vue 3.5+: destructured props are reactive (no need for toRefs)
const { count = 0, msg = "hello" } = defineProps<{
count?: number;
msg?: string;
}>();
// Limitation: cannot watch destructured prop directly
watch(() => count, (newVal) => { ... }); // PASS getter requireddefineProps()// Vue 3.5+:解构后的 props 保持响应式(无需 toRefs)
const { count = 0, msg = "hello" } = defineProps<{
count?: number;
msg?: string;
}>();
// 限制:无法直接监听解构后的 prop
watch(() => count, (newVal) => { ... }); // 必须使用 getter 包装useTemplateRef()useTemplateRef()useTemplateRef()import { useTemplateRef } from "vue";
const inputEl = useTemplateRef<HTMLInputElement>("input");
// "input" matches the ref="input" attribute in template, not the variable nameuseTemplateRef(dynamicRefId)useTemplateRef()import { useTemplateRef } from "vue";
const inputEl = useTemplateRef<HTMLInputElement>("input");
// "input" 与模板中的 ref="input" 属性匹配,而非变量名useTemplateRef(dynamicRefId)onWatcherCleanup()onWatcherCleanup()import { watch, onWatcherCleanup } from "vue";
watch(userId, async (newId) => {
const controller = new AbortController();
onWatcherCleanup(() => controller.abort());
// ... fetch with signal
});import { watch, onWatcherCleanup } from "vue";
watch(userId, async (newId) => {
const controller = new AbortController();
onWatcherCleanup(() => controller.abort());
// ... 使用 signal 发起请求
});useId()useId()import { useId } from "vue";
const id = useId();import { useId } from "vue";
const id = useId();deferdefer<Teleport defer><Teleport defer to="#container">Content</Teleport>
<div id="container"></div><Teleport defer><Teleport defer to="#container">内容</Teleport>
<div id="container"></div>defineAsyncComponent()hydrateimport { defineAsyncComponent, hydrateOnVisible } from "vue";
const AsyncComp = defineAsyncComponent({
loader: () => import("./Comp.vue"),
hydrate: hydrateOnVisible(),
});defineAsyncComponent()hydrateimport { defineAsyncComponent, hydrateOnVisible } from "vue";
const AsyncComp = defineAsyncComponent({
loader: () => import("./Comp.vue"),
hydrate: hydrateOnVisible(),
});| Anti-Pattern | Why It's Wrong | The Fix |
|---|---|---|
Destructuring | Captures snapshot, loses reactivity | Access via |
| Compile-time error — destructured props can't be watched directly | Use getter wrapper: |
| Ambiguous execution order | Use computed filtered array |
| Broken state on reorder | Use stable database IDs |
| Mutating props | Violates one-way data flow | Emit events or use |
| XSS vulnerability | Sanitize with DOMPurify |
| Mixins in Vue 3 | Opaque, collision-prone | Replace with composables |
| Module-scope side effects in composable | Shared across instances | Scope in |
| Replacement breaks reactivity | Use |
| Watcher without cleanup | Memory leaks, race conditions | Use |
| Options API in new Vue 3 code | Ecosystem move to Composition API | Use |
| Plain ref for template references | No dynamic ref support, name-matching fragile | Use |
| 反模式 | 问题所在 | 修复方案 |
|---|---|---|
Vue < 3.5 中解构 | 仅捕获快照,丢失响应式 | 通过 |
| Vue 3.5+ 中直接监听解构后的 prop | 编译错误——解构后的 prop 无法直接监听 | 使用 getter 包装: |
同一元素上同时使用 | 执行顺序模糊 | 使用计算属性过滤数组 |
| 重排时状态异常 | 使用稳定的数据库 ID |
| 修改 props | 违背单向数据流 | 触发事件或使用 |
对用户内容使用 | XSS 漏洞 | 使用 DOMPurify 进行 sanitize |
| Vue 3 中使用 Mixins | 不透明、易冲突 | 替换为组合式函数 |
| 组合式函数中存在模块级副作用 | 实例间共享副作用 | 限制在 |
对可替换状态使用 | 替换后丢失响应式 | 使用 |
| 监听器未清理 | 内存泄漏、竞态条件 | 使用 |
| 新项目中使用 Options API | 生态已转向 Composition API | 使用 |
| 模板引用使用普通 ref | 不支持动态 ref、名称匹配脆弱 | 使用 |
accessibilityfrontend-patternstypescriptcoding-standardsaccessibilityfrontend-patternstypescriptcoding-standards