From vue-coder
Vue 2 维护与开发最佳实践指南 - Options API、Vuex 及向 Vue 3 迁移准备。 当用户说"Vue 2组件"、"Options API"、"Vuex"、"Vue 2项目"、"Vue 2迁移"、"Vue mixin"、"Vue 2最佳实践"时使用此技能。 涵盖:Options API 规范(选项顺序、props 验证)、Vuex 模块化(namespaced modules)、逻辑复用(避免 mixin,使用工具函数)、迁移准备(停止使用 Filters、引入 Composition API 插件)。 提供 Vue 2 代码示例、反模式警告和迁移建议。
How this skill is triggered — by the user, by Claude, or both
Slash command
/vue-coder:vue2-best-practicesThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
本技能旨在指导开发者维护现有的 Vue 2 项目,编写**清晰、可预测**的 Options API 代码,并为未来迁移到 Vue 3 做准备。
本技能旨在指导开发者维护现有的 Vue 2 项目,编写清晰、可预测的 Options API 代码,并为未来迁移到 Vue 3 做准备。 核心原则:规范化 Options API、谨慎使用 Mixins、组件解耦。
namecomponentspropsdatacomputedwatchlifecycle hooks (created, mounted, etc.)methodsdata 必须始终是一个返回对象的函数,防止组件实例间状态污染。new Vue()) 进行通信,这会导致事件流难以追踪。namespaced: true) 来组织 Store。mapState, mapGetters, mapActions 简化组件内的调用。methods 或生命周期钩子中使用箭头函数,这会导致 this 指向错误。ref。computed 属性来处理派生数据,而不是滥用 watch。Vue.prototype 上挂载过多全局变量。$listeners)。<script setup>),以便逐步过渡到 Vue 3 的写法。<template>
<div class="user-card">
<h3>{{ formattedName }}</h3>
<p>{{ user.email }}</p>
<button @click="handleEdit">编辑</button>
</div>
</template>
<script>
// ✅ 遵循选项顺序规范
export default {
name: 'UserCard', // 1. name
components: { // 2. components
EditButton
},
props: { // 3. props - 带类型验证
user: {
type: Object,
required: true,
validator: (value) => ['id', 'name', 'email'].every(key => key in value)
}
},
data() { // 4. data - 必须是函数
return {
isEditing: false
}
},
computed: { // 5. computed
formattedName() {
return this.user.name.toUpperCase()
}
},
watch: { // 6. watch
'user.id': {
handler(newId) {
this.fetchUserData(newId)
},
immediate: true
}
},
created() { // 7. 生命周期钩子
this.initializeComponent()
},
mounted() {
this.setupEventListeners()
},
methods: { // 8. methods - 避免箭头函数
handleEdit() {
this.$emit('edit', this.user.id)
},
fetchUserData(id) {
// 数据获取逻辑
},
initializeComponent() {
// 初始化逻辑
},
setupEventListeners() {
// 事件监听
}
}
}
</script>
// store/modules/user.js
// ✅ 使用命名空间模块
export default {
namespaced: true,
state: () => ({
user: null,
token: null,
loading: false
}),
getters: {
isLoggedIn: state => !!state.token,
displayName: state => state.user?.name ?? '访客'
},
// Mutations 必须是同步的
mutations: {
SET_USER(state, user) {
state.user = user
},
SET_TOKEN(state, token) {
state.token = token
},
SET_LOADING(state, loading) {
state.loading = loading
}
},
// Actions 处理异步逻辑
actions: {
async login({ commit }, credentials) {
commit('SET_LOADING', true)
try {
const { user, token } = await authService.login(credentials)
commit('SET_USER', user)
commit('SET_TOKEN', token)
return { success: true }
} catch (error) {
return { success: false, error: error.message }
} finally {
commit('SET_LOADING', false)
}
},
logout({ commit }) {
commit('SET_USER', null)
commit('SET_TOKEN', null)
}
}
}
<!-- 组件中使用 Vuex -->
<template>
<div v-if="isLoggedIn">
<p>欢迎, {{ displayName }}</p>
<button @click="logout">退出</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
name: 'UserStatus',
computed: {
// ✅ 使用 map 辅助函数
...mapState('user', ['loading']),
...mapGetters('user', ['isLoggedIn', 'displayName'])
},
methods: {
...mapActions('user', ['logout'])
}
}
</script>
// ❌ 避免 Mixin
const userMixin = {
data() {
return { user: null }
},
methods: {
fetchUser() { /* ... */ }
}
}
// ✅ 使用工具函数
// utils/user.js
export function createUserService() {
return {
user: null,
async fetchUser(id) {
this.user = await api.getUser(id)
return this.user
}
}
}
// 组件中使用
import { createUserService } from '@/utils/user'
export default {
data() {
return {
userService: createUserService()
}
},
async created() {
await this.userService.fetchUser(this.userId)
}
}
<script>
export default {
props: {
// ✅ 基础类型验证
title: String,
// ✅ 多种可能的类型
value: [String, Number],
// ✅ 必填字段
userId: {
type: [String, Number],
required: true
},
// ✅ 带默认值
size: {
type: String,
default: 'medium',
validator: (value) => ['small', 'medium', 'large'].includes(value)
},
// ✅ 对象/数组默认值使用工厂函数
config: {
type: Object,
default: () => ({
theme: 'light',
locale: 'zh-CN'
})
},
// ✅ 自定义验证
email: {
type: String,
validator: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
}
}
}
</script>
<template>
<div>
<p>计数: {{ count }}</p>
<button @click="increment">+1</button>
</div>
</template>
<script>
// Vue 2.7+ 可以使用 Composition API
import { ref, computed, onMounted } from 'vue'
export default {
name: 'Counter',
// ✅ 渐进式迁移:setup 函数
setup() {
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
onMounted(() => {
console.log('Counter mounted')
})
return {
count,
doubled,
increment
}
}
}
</script>
# 规范化 Options 顺序
/vue-coder 重新排列这个组件的选项顺序,使其符合最佳实践。
# 移除 Mixin
/vue-coder 分析这个组件使用的 Mixin,尝试将其重构为普通的函数导入或 HOC。
# Vuex 模块化
/vue-coder 将这个庞大的 Vuex store 拆分为独立的命名空间模块。
npx claudepluginhub protagonistss/ithinku-plugins --plugin vue-coderDelivers Vue 3 best practices for Composition API script setup, composables, ref/reactive patterns, Pinia state management, and Nuxt apps. Activates on .vue files and Vue triggers.
Guides Vue.js 3 Composition API patterns, component architecture, reactivity, Pinia state management, Vue Router, and Nuxt SSR. Activates for Vue, Nuxt, Vite, or Pinia projects.
Vue 3 conventions, Composition API patterns, SFC structure, reactivity, composables, and TypeScript integration. Invoke whenever task involves any interaction with Vue code — writing, reviewing, refactoring, debugging, or understanding .vue files, composables, and Vue component architecture.