Vue3 组合式 API 示例指南 🚀

响应式数据基础

使用 reactive()ref() 创建响应式数据是组合式API的核心:

import { reactive, ref } from 'vue'

const state = reactive({
  count: 0,
  message: 'Hello Vue3!'
})

const counter = ref(0)
vue_component

计算属性与侦听器

通过 computed() 实现响应式衍生数据,watch() 监听变化:

const doubleCount = computed(() => state.count * 2)

watch(counter, (newVal) => {
  console.log(`Counter changed to ${newVal}`)
})
computed_property

生命周期钩子

组合式API提供更灵活的生命周期控制:

onMounted(() => {
  console.log('组件已挂载')
})

onUnmounted(() => {
  console.log('组件即将卸载')
})
lifecycle_hooks

扩展阅读

想要深入了解Vue3组合式API的原理?点击这里查看官方文档 获取更详细的教程和最佳实践 ✅

实用技巧

  • 使用 toRefs() 将响应式对象转换为普通对象
  • 通过 effect() 实现副作用操作
  • 掌握 shallowReactive()shallowRef() 的使用场景
vue3_composition_api