Vue Component Refactoring Skill
Use when encountering Vue SFCs exceeding 500 lines (especially 1000+ line "monster" files).
Trigger Conditions
- Single
.vue file exceeds 500 lines
- 50+ methods/functions in one
<script> block
- Mixed API styles (Options API + Composition API in same file)
- Multiple responsibilities in one component (data, UI, interaction, API calls)
Refactoring Protocol
Phase 1: Blueprint-First Analysis (NO CODE CHANGES)
Read the full file and map its structure:
- Template line range
- Script line range
- Style line range
- Count: functions, refs, computeds, watches, console.logs
Identify logical boundaries for extraction:
- Data/Grid generation →
useComponentData.js
- Status/State calculations →
useComponentStatus.js
- Click/Interaction handlers →
useComponentInteraction.js
- Drag/Drop/Animation →
useComponentDrag.js
- API calls → keep in interaction composable or separate
useComponentApi.js
Identify UI sub-components:
- Complex popup →
ComponentPopup.vue
- Repeated v-for items →
ComponentItem.vue
- Complex cards →
ComponentCard.vue
Design Props/Emits flow:
- Parent → Child: data, state flags, configuration
- Child → Parent:
@confirm, @cancel, @update:show, custom events
Output blueprint and wait for [APPROVE] before coding.
Phase 2: Step-by-Step Execution
Order of creation:
composables/useComponentData.js — data generation
composables/useComponentStatus.js — computed state
composables/useComponentInteraction.js — event handlers
composables/useComponentDrag.js — (if applicable)
- UI sub-components (popups, cards, items)
- Final: Rewrite main component's
<script> section
File creation pattern (use Python scripts for bulk creation):
import os
BASE = os.path.expanduser("~/project/src/composables")
os.makedirs(BASE, exist_ok=True)
with open(os.path.join(BASE, 'useComponentData.js'), 'w') as f:
f.write(content)
Phase 3: Main Component Rewrite
Strategy: Replace ONLY the <script> section, preserve <template> and <style> unchanged.
# Extract sections
template = lines[:script_start]
style = lines[style_start:]
# Create new script with composable imports
new_script = '''<script setup>
import { useComponentData } from '../composables/useComponentData'
import { useComponentStatus } from '../composables/useComponentStatus'
// ... more imports
const props = defineProps({...})
const emit = defineEmits([...])
const { ... } = useComponentData(props)
const { ... } = useComponentStatus()
// Keep template-referenced functions/refs here
defineExpose({...})
</script>'''
# Combine
new_content = f'{template}\n{new_script}\n{style}'
Phase 4: Verification
Syntax balance check:
open_braces = script_content.count('{')
close_braces = script_content.count('}')
assert open_braces == close_braces
Template ref audit:
- Extract all variable references from template (
{{ var }}, :prop="var", v-if="var")
- Verify each referenced variable exists in the new script
Critical checks:
defineExpose preserved (for parent component access)
provide/inject pairs preserved
- All event handlers wired correctly
- Props types match original
Pitfalls
- DO NOT change template logic in first pass — preserve DOM structure, only replace script
- DO NOT delete business logic — API parameters, role checks, type judgments must remain
- Watch for
uni.$emit/$on — ensure event bus calls are preserved or migrated properly
cloneDeep usage — if drag/drop uses deep clone, keep it in the drag composable
provide/inject — keep in main component, don't move to composables
- Mixed API style — if original uses
data() + methods(), convert ALL to Composition API (ref/computed) in the refactor
- console.log cleanup — remove debug logs during refactor (use conditional logger if needed)
Target Structure After Refactor
components/
├── ComponentName.vue [~300 lines] main assembly layer
├── ComponentPopup.vue [~100-300 lines] extracted popup
└── ComponentCard.vue [~100-200 lines] extracted card
composables/
├── useComponentData.js [~100-250 lines]
├── useComponentStatus.js [~150-400 lines]
├── useComponentInteraction.js [~150-450 lines]
└── useComponentDrag.js [~100-200 lines] (optional)
Success Metrics
- Main component reduced to <400 lines
- Each composable has single responsibility
- All template refs resolve correctly
- Business logic unchanged (verified by test or manual check)
- Zero console.log remaining in production code
1---
2name: vue-component-refactoring
3category: software-development
4description: Refactor giant Vue single-file components (>500 lines) into maintainable structure using composables and sub-components. Covers blueprint-first analysis, extraction patterns, and verification steps for Vue 3 / Uni-app projects.
5metadata:
6 source: https://skillmd.com/skills/ichichuang/vue-component-refactoring
7---
8
9# Vue Component Refactoring Skill
10
11Use when encountering Vue SFCs exceeding 500 lines (especially 1000+ line "monster" files).
12
13## Trigger Conditions
14- Single `.vue` file exceeds 500 lines
15- 50+ methods/functions in one `<script>` block
16- Mixed API styles (Options API + Composition API in same file)
17- Multiple responsibilities in one component (data, UI, interaction, API calls)
18
19## Refactoring Protocol
20
21### Phase 1: Blueprint-First Analysis (NO CODE CHANGES)
22
231. **Read the full file** and map its structure:
24 - Template line range
25 - Script line range
26 - Style line range
27 - Count: functions, refs, computeds, watches, console.logs
28
292. **Identify logical boundaries** for extraction:
30 - **Data/Grid generation** → `useComponentData.js`
31 - **Status/State calculations** → `useComponentStatus.js`
32 - **Click/Interaction handlers** → `useComponentInteraction.js`
33 - **Drag/Drop/Animation** → `useComponentDrag.js`
34 - **API calls** → keep in interaction composable or separate `useComponentApi.js`
35
363. **Identify UI sub-components**:
37 - Complex popup → `ComponentPopup.vue`
38 - Repeated v-for items → `ComponentItem.vue`
39 - Complex cards → `ComponentCard.vue`
40
414. **Design Props/Emits flow**:
42 - Parent → Child: data, state flags, configuration
43 - Child → Parent: `@confirm`, `@cancel`, `@update:show`, custom events
44
455. **Output blueprint** and wait for `[APPROVE]` before coding.
46
47### Phase 2: Step-by-Step Execution
48
49**Order of creation**:
501. `composables/useComponentData.js` — data generation
512. `composables/useComponentStatus.js` — computed state
523. `composables/useComponentInteraction.js` — event handlers
534. `composables/useComponentDrag.js` — (if applicable)
545. UI sub-components (popups, cards, items)
556. **Final**: Rewrite main component's `<script>` section
56
57**File creation pattern** (use Python scripts for bulk creation):
58```python
59import os
60BASE = os.path.expanduser("~/project/src/composables")
61os.makedirs(BASE, exist_ok=True)
62with open(os.path.join(BASE, 'useComponentData.js'), 'w') as f:
63 f.write(content)
64```
65
66### Phase 3: Main Component Rewrite
67
68**Strategy**: Replace ONLY the `<script>` section, preserve `<template>` and `<style>` unchanged.
69
70```python
71# Extract sections
72template = lines[:script_start]
73style = lines[style_start:]
74
75# Create new script with composable imports
76new_script = '''<script setup>
77import { useComponentData } from '../composables/useComponentData'
78import { useComponentStatus } from '../composables/useComponentStatus'
79// ... more imports
80
81const props = defineProps({...})
82const emit = defineEmits([...])
83
84const { ... } = useComponentData(props)
85const { ... } = useComponentStatus()
86
87// Keep template-referenced functions/refs here
88defineExpose({...})
89</script>'''
90
91# Combine
92new_content = f'{template}\n{new_script}\n{style}'
93```
94
95### Phase 4: Verification
96
971. **Syntax balance check**:
98 ```python
99 open_braces = script_content.count('{')
100 close_braces = script_content.count('}')
101 assert open_braces == close_braces
102 ```
103
1042. **Template ref audit**:
105 - Extract all variable references from template (`{{ var }}`, `:prop="var"`, `v-if="var"`)
106 - Verify each referenced variable exists in the new script
107
1083. **Critical checks**:
109 - `defineExpose` preserved (for parent component access)
110 - `provide`/`inject` pairs preserved
111 - All event handlers wired correctly
112 - Props types match original
113
114## Pitfalls
115
116- **DO NOT change template logic** in first pass — preserve DOM structure, only replace script
117- **DO NOT delete business logic** — API parameters, role checks, type judgments must remain
118- **Watch for `uni.$emit/$on`** — ensure event bus calls are preserved or migrated properly
119- **`cloneDeep` usage** — if drag/drop uses deep clone, keep it in the drag composable
120- **`provide/inject`** — keep in main component, don't move to composables
121- **Mixed API style** — if original uses `data()` + `methods()`, convert ALL to Composition API (`ref`/`computed`) in the refactor
122- **console.log cleanup** — remove debug logs during refactor (use conditional logger if needed)
123
124## Target Structure After Refactor
125
126```
127components/
128├── ComponentName.vue [~300 lines] main assembly layer
129├── ComponentPopup.vue [~100-300 lines] extracted popup
130└── ComponentCard.vue [~100-200 lines] extracted card
131composables/
132├── useComponentData.js [~100-250 lines]
133├── useComponentStatus.js [~150-400 lines]
134├── useComponentInteraction.js [~150-450 lines]
135└── useComponentDrag.js [~100-200 lines] (optional)
136```
137
138## Success Metrics
139
140- Main component reduced to <400 lines
141- Each composable has single responsibility
142- All template refs resolve correctly
143- Business logic unchanged (verified by test or manual check)
144- Zero console.log remaining in production code