Vue 3 的 Composition API 是现代 Vue 开发的核心。作为冉冉博客的 Vue 教程系列,今天分享 10 个实战技巧。
一、setup 语法糖
<script setup> 让代码更简洁:
<script setup>
import { ref, computed, watch } from 'vue'
// 无需 return,直接使用
const count = ref(0)
const doubled = computed(() => count.value * 2)
watch(count, (newVal) => {
console.log('count changed:', newVal)
})
</script>
二、响应式解构
<script setup>
import { toRefs } from 'vue'
const props = defineProps({
title: String,
count: Number
})
// 解构后保持响应式
const { title, count } = toRefs(props)
// 或者使用 toRef
import { toRef } from 'vue'
const title = toRef(props, 'title')
</script>
三、组合式函数封装
// composables/useCounter.js
export function useCounter(initial = 0) {
const count = ref(initial)
const increment = () => count.value++
const decrement = () => count.value--
const reset = () => count.value = initial
return { count, increment, decrement, reset }
}
// 使用
<script setup>
import { useCounter } from '@/composables/useCounter'
const { count, increment, decrement } = useCounter(10)
</script>
四、provide / inject 跨组件传值
// Parent.vue
import { provide, ref } from 'vue'
const theme = ref('dark')
provide('theme', theme)
// Child.vue
import { inject } from 'vue'
const theme = inject('theme')
const updateTheme = (newTheme) => {
theme.value = newTheme
}
provide('updateTheme', updateTheme)
五、异步组件与 Suspense
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncModal = defineAsyncComponent(() =>
import('./components/Modal.vue')
)
</script>
<template>
<Suspense>
<template #default>
<AsyncModal />
</template>
<template #fallback>
<Loading />
</template>
</Suspense>
</template>
六、computed 的高级用法
import { computed, ref } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
// 可写计算属性
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(value) {
[firstName.value, lastName.value] = value.split(' ')
}
})
// 使用
console.log(fullName.value) // 'John Doe'
fullName.value = 'Jane Smith'
console.log(firstName.value) // 'Jane'
七、watchEffect 自动依赖追踪
<script setup>
import { ref, watchEffect } from 'vue'
const todoId = ref(1)
const todo = ref(null)
watchEffect(async () => {
// 自动追踪 todoId 变化
const response = await fetch(`/api/todos/${todoId.value}`)
todo.value = await response.json()
console.log('Fetched:', todo.value)
})
</script>
八、Teleport 传送门
<template>
<button @click="showModal = true">打开弹窗</button>
<Teleport to="body">
<div v-if="showModal" class="modal">
<h3>弹窗内容</h3>
<button @click="showModal = false">关闭</button>
</div>
</Teleport>
</template>
九、CSS 变量绑定
<script setup>
import { ref } from 'vue'
const color = ref('#ff0000')
</script>
<template>
<div :style="{ '--theme-color': color }">
<button class="btn">按钮</button>
</div>
</template>
<style scoped>
.btn {
background: var(--theme-color);
}
</style>
十、TypeScript 配合 Composition API
<script setup lang="ts">
import { ref, computed } from 'vue'
interface User {
id: number
name: string
email: string
}
const users = ref<User[]>([])
const searchQuery = ref('')
const filteredUsers = computed<User[]>(() => {
return users.value.filter(user =>
user.name.includes(searchQuery.value)
)
})
const addUser = (user: Omit<User, 'id'>): User => {
const newUser: User = {
id: Math.max(...users.value.map(u => u.id)) + 1,
...user
}
users.value.push(newUser)
return newUser
}
</script>
Vue 3 Composition API 是一套强大的工具。掌握这些技巧,能让你的 Vue 项目代码更加优雅和可维护。更多 Vue 实战教程,欢迎持续关注冉冉博客。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END














暂无评论内容