Technical Sharing December 18, 2024 约 22 分钟阅读

Deep Dive into Vue 3 Composition API

Vue 3's Composition API is a revolutionary feature that changes the way we write Vue components.

Why Composition API?

In Vue 2, we used the Options API to organize component code. While this approach is simple and easy to understand, when dealing with complex components, related logic is often scattered across different options, making the code difficult to maintain.

The Composition API solves this problem by organizing related logic together.

Core Concepts

1. setup Function

<script setup>
import { ref, computed, onMounted } from 'vue'

const count = ref(0)
const doubleCount = computed(() => count.value * 2)

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

onMounted(() => {
  console.log('Component mounted')
})
</script>

2. Reactive References

import { ref, reactive } from 'vue'

// Use ref for primitive types
const name = ref('Vue 3')

// Use reactive for object types
const user = reactive({
  name: 'John',
  age: 30
})

3. Computed Properties

import { computed } from 'vue'

const fullName = computed(() => {
  return `${firstName.value} ${lastName.value}`
})

Lifecycle Hooks

import { onMounted, onUnmounted, onUpdated } from 'vue'

onMounted(() => {
  // Executed after component is mounted
})

onUnmounted(() => {
  // Executed before component is unmounted
})

onUpdated(() => {
  // Executed after component is updated
})

Composables

One of the most powerful features of the Composition API is Composables:

// useCounter.js
import { ref, computed } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  
  const increment = () => count.value++
  const decrement = () => count.value--
  const double = computed(() => count.value * 2)
  
  return {
    count,
    increment,
    decrement,
    double
  }
}

Best Practices

  1. Logic Reuse: Use Composables to reuse logic
  2. Separation of Concerns: Organize related logic together
  3. Type Safety: Use with TypeScript for better type support
  4. Progressive Adoption: You can mix Options API and Composition API in the same project

The Composition API brings more powerful logic reuse capabilities and better code organization to Vue 3, making it an important tool for modern Vue development.