Vue3 组合式 API
Vue3 提供两套组织组件逻辑的方式:选项式 API 与组合式 API。组合式 API 把所有相关的状态与函数集中在 setup(或 <script setup>)中,按「功能」而非「选项类型」组织代码,复用与维护都更顺手,是 Vue3 官方推荐的主力写法。
选项式 API 的问题
data、methods、computed、watch 被强制分到不同选项中,一个功能的代码常被拆散到多处;多个组件想复用同一段逻辑只能借助 mixin,容易命名冲突。组合式 API 正是为根治这两个痛点而生。
setup 与 script setup
先看最原始的 setup 函数写法:
import { ref } from 'vue'
export default {
setup() {
const count = ref(0) // 声明响应式状态
const add = () => count.value++
return { count, add } // 返回给模板使用
},
}
更常用的是 <script setup>,顶层变量与函数自动暴露给模板,无需 return:
<script setup>
import { ref } from 'vue'
const count = ref(0)
const add = () => count.value++
</script>
ref 与 reactive
ref 可包裹任意值,reactive 用于对象,二者都让数据具备响应性:
const num = ref(0) // 读取、修改需用 .value
const user = reactive({ name: '张三' }) // 对象深层自动响应
num.value = 5 // 修改 ref 用 .value
user.name = '李四' // 修改 reactive 直接赋值
computed 与 watch
计算属性依赖变化自动重算,watch 侦听数据变化并执行副作用:
const price = ref(100)
const total = computed(() => price.value * 2) // 派生状态,带缓存
watch(price, (newVal, oldVal) => {
console.log(`价格:${oldVal} → ${newVal}`) // 输出:价格:100 → 110
})
生命周期钩子
组合式写法用带 on 前缀的函数,在 setup 顶层注册:
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('挂载完成,可请求数据') // 输出:挂载完成,可请求数据
})
onUnmounted(() => {
console.log('卸载清理') // 输出:卸载清理
})
自定义组合函数
把「带状态」的逻辑抽成普通函数即可复用,任何组件按需解构、数据互不干扰:
// useCounter.js
import { ref } from 'vue'
export function useCounter(init = 0) {
const count = ref(init)
const add = () => count.value++
const reset = () => (count.value = init)
return { count, add, reset }
}
组件中使用:
import { useCounter } from './useCounter'
const { count, add } = useCounter(10)
console.log(count.value) // 输出:10
小结
组合式 API 让「相关代码放一起、通用逻辑可抽取」。新项目建议直接用 <script setup>,配合 ref、computed、watch 与自定义函数,代码清晰且易复用。