观语AI2026
24.3MB · 2026-04-03
你的 Vue 组件里是不是还在 data、methods、computed、watch 之间来回跳转?
而用 Composition API,一个 setup 函数搞定所有逻辑,代码量直降 80%,逻辑清晰到实习生都能看懂。
如果你受够了:
那么,这篇手把手实操指南,就是为你写的——
不用死记硬背,所有代码模板直接复制粘贴,今天就能用上!
很多新手觉得:“Options API 能用,为啥换?”
但真相是:Options API 在复杂组件中,逻辑天然割裂。
举个真实例子:写一个带防抖搜索 + 加载状态 + 错误提示的搜索框
Options API 写法:
data 里定义 keyword, loading, errormethods 里写 search(), debounce()watch 里 keyword 触发搜索mounted 里可能还要初始化默认值Composition API 写法:
const { keyword, loading, error, search } = useSearch()
一行代码,逻辑内聚,复用无痛。
这是 Vue3 官方推荐的写法,无需 return,自动暴露所有变量和方法。
实操代码模板(直接复制到项目)<template>
<div>
<input v-model="username" placeholder="请输入账号" />
<button @click="login" :disabled="isLoading">
{{ isLoading ? '登录中...' : '登录' }}
</button>
</div>
</template>
<script setup>
// 1. 定义响应式数据(替代 data)
import { ref } from 'vue'
const username = ref('') // 响应式字符串
const isLoading = ref(false) // 响应式布尔值
// 2. 定义方法(替代 methods)
const login = () => {
isLoading.value = true
// 模拟登录请求
setTimeout(() => {
console.log('登录成功,账号:', username.value)
isLoading.value = false
}, 1000)
}
// 3. 无需 return!<script setup> 自动暴露
</script>
ref vs reactive:响应式数据的“两大神器”,别再用混了记住口诀:**简单数据用 **ref,复杂对象用 reactive。
| 场景 | 推荐 API | 修改方式 | 模板中使用 |
|---|---|---|---|
| 字符串、数字、布尔值 | ref | count.value = 1 | {{ count }} |
| 对象、数组 | reactive | user.name = 'Tom' | {{ user.name }} |
ref 实操示例】import { ref } from 'vue'
const count = ref(0)
const increment = () => {
count.value++ // 必须加 .value!
}
import { reactive } from 'vue'
const user = reactive({
name: '',
age: 0,
hobbies: []
})
const updateUser = () => {
user.name = 'Alice' // 直接修改,不加 .value
user.hobbies.push('coding')
}
toRefs 解构 reactive 对象,保持响应式import { reactive, toRefs } from 'vue'
const user = reactive({ username: '', password: '' })
// 解构后仍响应式
const { username, password } = toRefs(user)
username.value = 'test' // 有效!
Vue3 生命周期需显式导入,更灵活,且避免无用代码。
| Vue2 | Vue3 |
|---|---|
mounted | onMounted |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
const list = ref([])
onMounted(async () => {
const res = await axios.get('/api/user/list')
list.value = res.data
})
</script>
ref 加 .value,导致响应式失效// 错误
const count = ref(0)
count = 1 // 页面不会更新!
// 正确
count.value = 1
reactive 创建简单数据// 错误
const count = reactive(0) // reactive 只接受对象/数组
count = 1 // 响应式丢失!
// 正确
const count = ref(0)
把重复代码(如表单校验、请求封装、本地存储)抽成 Hook,多个组件直接引入,少写 80% 代码。
hooks/useForm.js// hooks/useForm.js
import { ref } from 'vue'
export const useForm = (rules) => {
const form = ref({})
const errors = ref({})
const validate = () => {
let isValid = true
for (const key in rules) {
const rule = rules[key]
if (!form.value[key] && rule.required) {
errors.value[key] = rule.message
isValid = false
} else {
errors.value[key] = ''
}
}
return isValid
}
return { form, errors, validate }
}
<script setup>
import { useForm } from '@/hooks/useForm'
const { form, errors, validate } = useForm({
username: { required: true, message: '请输入账号' },
password: { required: true, message: '请输入密码' }
})
const login = () => {
if (validate()) {
console.log('提交数据:', form.value)
}
}
</script>
<template>
<div>
<input v-model="form.username" />
<span v-if="errors.username" class="error">{{ errors.username }}</span>
<input type="password" v-model="form.password" />
<span v-if="errors.password" class="error">{{ errors.password }}</span>
<button @click="login">登录</button>
</div>
</template>
useXXX 模式Composition API 的价值,不只是“新语法”,而是用函数式思维组织逻辑,让代码可读、可测、可复用。
当你不再为找变量翻遍整个文件,你就知道——这波升级,值了。
各位互联网搭子,要是这篇文章成功引起了你的注意,别犹豫,关注、点攒、评论、分享走一波,让我们把这份默契延续下去,一起在知识的海洋里乘风破浪!