home / skills / long36708 / longmo-skills / vue2-best-practices

vue2-best-practices skill

/skills/vue2-best-practices

This skill guides maintaining Vue 2 projects with standardized Options API, safer mixins, and prepared migration steps to Vue 3, improving stability.

npx playbooks add skill long36708/longmo-skills --skill vue2-best-practices

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.7 KB
---
name: vue2-best-practices
description: Vue 2 维护与开发最佳实践指南,涵盖 Options API, Vuex 及向 Vue 3 迁移的准备。
---

# Vue 2 Best Practices (Legacy & Maintenance)

## 🌟 技能核心:稳定维护与平滑过渡

本技能旨在指导开发者维护现有的 Vue 2 项目,编写**清晰、可预测**的 Options API 代码,并为未来迁移到 Vue 3 做准备。
**核心原则**:规范化 Options API、谨慎使用 Mixins、组件解耦。

## 🧠 Core Principles (核心原则)

### 1. Options API 规范

- **Order of Options**: 遵循一致的选项顺序:
    1. `name`
    2. `components`
    3. `props`
    4. `data`
    5. `computed`
    6. `watch`
    7. `lifecycle hooks` (created, mounted, etc.)
    8. `methods`
- **Data Function**: `data` 必须始终是一个返回对象的函数,防止组件实例间状态污染。
- **Props Validation**: 始终为 props 定义详细的类型验证和默认值。

### 2. 逻辑复用 (Logic Reuse)

- **Mixins**:
    - **警告**: 尽量减少 Mixins 的使用。它们会导致命名冲突和隐式依赖,使代码难以理解。
    - **替代**: 如果必须复用逻辑,考虑使用 HOC (Higher Order Components) 或 Scoped Slots (作用域插槽)。
    - **规范**: 如果使用 Mixin,必须加上明确的前缀,并在组件注释中说明来源。
- **Utility Functions**: 将纯逻辑提取为独立的 JS 文件导入使用。

### 3. 组件通信

- **Event Bus**:
    - **警告**: 避免滥用全局 Event Bus (`new Vue()`) 进行通信,这会导致事件流难以追踪。
    - **替代**: 使用 Vuex 或 Props/Events 进行父子通信。
- **Props Down, Events Up**: 严格遵守单向数据流原则。不要直接修改 prop。

## 🧩 状态管理 (Vuex)

- **Vuex 3**:
    - **Modules**: 始终使用 Namespaced Modules (`namespaced: true`) 来组织 Store。
    - **MapHelpers**: 使用 `mapState`, `mapGetters`, `mapActions` 简化组件内的调用。
    - **Mutations**: 必须是同步的。异步逻辑放在 Actions 中。
    - **Strict Mode**: 在开发环境开启严格模式,确保状态只能通过 mutations 修改。

## 注意事项:

使用 `this.$set` 添加新属性
使用 `Vue.set` 或 `this.$set` 修改数组索引
```ts
// 添加新属性
this.$set(this.user, 'age', 25)

// 修改数组索引
this.$set(this.items, 0, newItem)

// 修改数组长度
this.items.splice(newLength)
```
合理拆分组件,避免过度耦合

使用 v-if 和 v-show 合理选择
使用 key 优化列表渲染
使用 Object.freeze() 冻结大对象

## 🚫 反模式 (Anti-Patterns)

- ❌ **Arrow Functions in Methods**: 不要在 `methods` 或生命周期钩子中使用箭头函数,这会导致 `this` 指向错误。
- ❌ **Direct DOM Manipulation**: 避免使用 jQuery 或直接操作 DOM,始终通过数据驱动视图。如果必须操作,使用 `ref`。
- ❌ **Over-reliance on Watchers**: 优先使用 `computed` 属性来处理派生数据,而不是滥用 `watch`。
- ❌ **Implicit Global Variables**: 避免直接在 `Vue.prototype` 上挂载过多全局变量。

## 🔄 迁移准备 (Migration Readiness)

- **Avoid Deprecated Features**: 停止使用即将在 Vue 3 移除的特性(如 Filters, Inline Templates, `$listeners`)。
- **Composition API Plugin**: 在 Vue 2.7+ 中,尝试引入 Composition API (`<script setup>`),以便逐步过渡到 Vue 3 的写法。

## 🎨 常用指令示例

```bash
# 规范化 Options 顺序
/vue-coder 重新排列这个组件的选项顺序,使其符合最佳实践。

# 移除 Mixin
/vue-coder 分析这个组件使用的 Mixin,尝试将其重构为普通的函数导入或 HOC。

# Vuex 模块化
/vue-coder 将这个庞大的 Vuex store 拆分为独立的命名空间模块。
```

Overview

This skill provides practical best practices for maintaining and developing Vue 2 applications with a focus on stable Options API code, clear state management with Vuex, and preparing projects for an eventual move to Vue 3. It emphasizes predictable patterns, reduced coupling, and safe logic reuse to keep legacy codebases maintainable and migration-ready.

How this skill works

The skill inspects component structure and Vuex usage, enforcing a consistent Options API order and prop/data conventions. It flags risky patterns (mixins, global event buses, arrow functions in methods) and suggests safer alternatives like utility functions, namespaced Vuex modules, and Composition API adoption in Vue 2.7+ for progressive migration.

When to use it

  • When maintaining or refactoring an existing Vue 2 codebase to improve readability and reliability.
  • Before starting a migration plan toward Vue 3 to identify deprecated patterns and compatibility risks.
  • When standardizing component structure across a team to reduce onboarding friction.
  • During code reviews to catch anti-patterns (mixins abuse, direct DOM manipulation, implicit globals).
  • When reorganizing Vuex into scalable, namespaced modules for large applications.

Best practices

  • Follow a consistent Options order: name, components, props, data, computed, watch, lifecycle hooks, methods.
  • Keep data as a function returning an object to avoid shared mutable state between instances.
  • Prefer utility functions or HOCs over mixins; if mixins are used, prefix names and document sources.
  • Use props down / events up and avoid global event bus; prefer Vuex for cross-component state.
  • Organize Vuex with namespaced modules, put async logic in actions, and enable strict mode in dev.
  • Avoid arrow functions in methods and lifecycle hooks; use this.$set or Vue.set to add reactive properties.

Example use cases

  • Reformatting components to a standardized Options order for a large legacy project.
  • Refactoring a tangled mixin into explicit utility imports and a namespaced Vuex module.
  • Auditing a repository to remove filters, inline templates, and other Vue 2 features incompatible with Vue 3.
  • Converting derived data from watchers to computed properties to improve performance and clarity.
  • Introducing the Composition API plugin in Vue 2.7+ to start writing migration-friendly code.

FAQ

Should I remove all mixins immediately?

No. Audit their usage first: prioritize replacing ambiguous or conflicting mixins with utility functions or HOCs. Keep documented, prefixed mixins temporarily while refactoring.

When should I enable Vuex strict mode?

Enable strict mode in development to ensure state changes go through mutations. Disable in production for performance if needed.