Vue 3 Composition API 完全指南
Vue 3 引入了 Composition API,提供了更灵活的代码组织方式。
为什么需要 Composition API?
Options API 的问题
// Options API:逻辑分散在不同选项
export default {
data() {
return { count: 0, name: '' }
},
computed: {
double() { return this.count * 2 }
},
methods: {
increment() { this.count++ }
},
mounted() {
// 初始化逻辑
}
}
Composition API 的优势
// Composition API:逻辑集中
import { ref, computed, onMounted } from 'vue'
export default {
setup() {
const count = ref(0)
const double = computed(() => count.value * 2)
const increment = () => count.value++
onMounted(() => {
// 初始化逻辑
})
return { count, double, increment }
}
}
核心 API
ref
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++
reactive
import { reactive } from 'vue'
const state = reactive({
count: 0,
name: '张三'
})
state.count++
computed
import { computed } from 'vue'
const double = computed(() => count.value * 2)
watch
import { watch } from 'vue'
// 监听单个 ref
watch(count, (newVal, oldVal) => {
console.log(`count: ${oldVal} → ${newVal}`)
})
// 监听多个源
watch([count, name], ([newCount, newName]) => {
console.log(newCount, newName)
})
// 深度监听
watch(state, (newVal) => {
console.log(newVal)
}, { deep: true })
生命周期钩子
import { onMounted, onUpdated, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件挂载')
})
onUpdated(() => {
console.log('组件更新')
})
onUnmounted(() => {
console.log('组件卸载')
})
组合式函数(Composables)
// useCounter.js
import { ref } from 'vue'
export function useCounter(initial = 0) {
const count = ref(initial)
const increment = () => count.value++
const decrement = () => count.value--
return { count, increment, decrement }
}
// 使用
const { count, increment } = useCounter(10)