Vue 3 组件化开发最佳实践

前言

Vue 3 带来了全新的开发体验,Composition API 使组件开发更加灵活和高效。本文分享在实际项目中的组件化开发最佳实践。

一、组件基础

1.1 单文件组件

<template>
  <div class="my-component">
    <h1>{{ title }}</h1>
    <button @click="increment">{{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
const title = ref('Vue 3 组件')

const increment = () => {
  count.value++
}
</script>

<style scoped>
.my-component { padding: 20px; }
</style>

1.2 Composition API

使用 Composition API 组织逻辑,使代码更清晰易维护。

import { ref, computed, watch } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  const doubled = computed(() => count.value * 2)
  
  watch(count, (newVal) => {
    console.log(`计数变化为: ${newVal}`)
  })
  
  return { count, doubled }
}

二、Props 和 Emit

2.1 父子通信

// 子组件
<script setup>
defineProps({
  modelValue: String,
  disabled: Boolean
})

const emit = defineEmits(['update:modelValue', 'change'])

const handleClick = () => {
  emit('update:modelValue', 'new value')
  emit('change', 'event fired')
}
</script>

三、状态管理

3.1 使用 Pinia

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const isLoggedIn = computed(() => !!user.value)
  
  const login = (userData) => {
    user.value = userData
  }
  
  const logout = () => {
    user.value = null
  }
  
  return { user, isLoggedIn, login, logout }
})

四、组件通信模式

五、性能优化

5.1 代码分割

import { defineAsyncComponent } from 'vue'

const HeavyComponent = defineAsyncComponent(() =>
  import('./components/HeavyComponent.vue')
)

5.2 懒加载路由

const routes = [
  {
    path: '/user',
    component: () => import('./views/User.vue')
  }
]

六、最佳实践

总结

Vue 3 的组件化开发使前端项目更加有序和可维护。掌握这些最佳实践,能够构建高效的 Vue 应用。

标签: Vue 3 组件化 前端开发