元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
Vue3 基础
▶
环境搭建
安装与配置
项目创建
开发工具
▶
模板语法
插值表达式
指令系统
事件处理
▶
核心概念
▶
响应式系统
ref与reactive
计算属性
侦听器
▶
组合式API
setup函数
生命周期钩子
自定义Hooks
▶
组件开发
▶
组件基础
组件通信
Props详解
插槽机制
▶
高级组件
动态组件
异步组件
递归组件
▶
状态管理
▶
Vuex基础
状态存储
模块化
组合式写法
▶
Pinia
创建Store
状态操作
插件机制
发布时间:
2025-03-22 12:13
↑
☰
# Vue3 Setup函数详解 本文将详细介绍Vue3中的setup函数,包括其基本用法、特性和最佳实践。 ## Setup函数基础 ### 1. 基本语法 ```vue <script setup> import { ref, onMounted } from 'vue' // 声明响应式状态 const count = ref(0) // 声明方法 const increment = () => { count.value++ } // 生命周期钩子 onMounted(() => { console.log('Component mounted') }) </script> <template> <button @click="increment">Count is: {{ count }}</button> </template> ``` ### 2. 与Options API的对比 ```vue <!-- Options API --> <script> export default { data() { return { count: 0 } }, methods: { increment() { this.count++ } }, mounted() { console.log('Component mounted') } } </script> <!-- Composition API with setup --> <script setup> import { ref, onMounted } from 'vue' const count = ref(0) const increment = () => count.value++ onMounted(() => { console.log('Component mounted') }) </script> ``` ## Props和Emit ### 1. Props的使用 ```vue <script setup> import { defineProps } from 'vue' // 声明props const props = defineProps({ title: { type: String, required: true }, count: { type: Number, default: 0 } }) console.log(props.title) // 直接访问props </script> <template> <h1>{{ title }}</h1> <p>Count: {{ count }}</p> </template> ``` ### 2. Emit事件 ```vue <script setup> import { defineEmits } from 'vue' // 声明emit事件 const emit = defineEmits(['update', 'delete']) // 触发事件 const handleUpdate = () => { emit('update', { id: 1, data: 'new data' }) } const handleDelete = () => { emit('delete', 1) } </script> <template> <button @click="handleUpdate">Update</button> <button @click="handleDelete">Delete</button> </template> ``` ## 响应式系统集成 ### 1. 响应式变量 ```vue <script setup> import { ref, reactive, computed } from 'vue' // ref用于基本类型 const count = ref(0) // reactive用于对象 const state = reactive({ user: { name: 'John', age: 30 }, settings: { theme: 'dark' } }) // 计算属性 const doubleCount = computed(() => count.value * 2) const increment = () => { count.value++ state.user.age++ } </script> ``` ### 2. 监听器 ```vue <script setup> import { ref, watch, watchEffect } from 'vue' const searchQuery = ref('') const searchResults = ref([]) // 使用watch watch(searchQuery, async (newQuery) => { if (newQuery.trim()) { const response = await fetch(`/api/search?q=${newQuery}`) searchResults.value = await response.json() } else { searchResults.value = [] } }) // 使用watchEffect watchEffect(async () => { const query = searchQuery.value.trim() if (query) { const response = await fetch(`/api/search?q=${query}`) searchResults.value = await response.json() } }) </script> ``` ## 生命周期钩子 ```vue <script setup> import { onMounted, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount } from 'vue' onBeforeMount(() => { console.log('Before Mount') }) onMounted(() => { console.log('Mounted') }) onBeforeUpdate(() => { console.log('Before Update') }) onUpdated(() => { console.log('Updated') }) onBeforeUnmount(() => { console.log('Before Unmount') }) onUnmounted(() => { console.log('Unmounted') }) </script> ``` ## 依赖注入 ### 1. 提供数据 ```vue <script setup> import { provide, ref } from 'vue' // 提供响应式数据 const theme = ref('light') provide('theme', theme) // 提供方法 const updateTheme = () => { theme.value = theme.value === 'light' ? 'dark' : 'light' } provide('updateTheme', updateTheme) </script> ``` ### 2. 注入数据 ```vue <script setup> import { inject } from 'vue' // 注入数据和方法 const theme = inject('theme') const updateTheme = inject('updateTheme') // 设置默认值 const count = inject('count', 0) </script> ``` ## 最佳实践 ### 1. 组织代码结构 ```vue <script setup> import { ref, onMounted } from 'vue' import { useUserStore } from '@/stores/user' import { useTheme } from '@/composables/theme' // 组合式函数 const { theme, toggleTheme } = useTheme() // 状态管理 const userStore = useUserStore() // 本地状态 const localState = ref(null) // 生命周期钩子 onMounted(() => { // 初始化逻辑 }) // 方法定义 const handleAction = () => { // 处理逻辑 } </script> ``` ### 2. 类型支持 ```vue <script setup lang="ts"> import { ref } from 'vue' // 定义接口 interface User { id: number name: string email: string } // 使用类型 const user = ref<User>({ id: 1, name: 'John', email: 'john@example.com' }) // Props类型定义 const props = defineProps<{ title: string count?: number }>() // Emit类型定义 const emit = defineEmits<{ (e: 'update', id: number): void (e: 'delete', id: number): void }>() </script> ``` ### 3. 性能优化 ```vue <script setup> import { ref, shallowRef, markRaw } from 'vue' // 大数据使用shallowRef const bigData = shallowRef(new Array(1000).fill(0)) // 非响应式对象使用markRaw const staticData = markRaw({ // 大量静态数据 }) // 避免不必要的响应式 const constants = { MAX_COUNT: 100, MIN_COUNT: 0 } </script> ``` ## 注意事项 ### 1. 避免this的使用 ```vue <script setup> // 错误示例 - 不要使用this const wrongWay = { data: 'example', method() { console.log(this.data) // 避免使用this } } // 正确示例 - 直接使用变量 const data = 'example' const method = () => { console.log(data) } </script> ``` ### 2. 保持响应式 ```vue <script setup> import { ref, reactive } from 'vue' const count = ref(0) const state = reactive({ value: 0 }) // 错误 - 会失去响应性 const wrongCopy = count.value // 正确 - 保持响应性 const correctUse = () => count.value const { value } = state // 解构reactive对象会失去响应性 </script> ``` ## 总结 本文详细介绍了Vue3中setup函数的使用方法: 1. 基础概念 - 基本语法 - 与Options API的对比 - Props和Emit的使用 2. 响应式系统 - 响应式变量 - 计算属性 - 监听器 3. 高级特性 - 生命周期钩子 - 依赖注入 - TypeScript支持 4. 最佳实践 - 代码组织 - 性能优化 - 注意事项 通过合理使用setup函数,可以让Vue3组件的代码更加清晰、易维护。建议在实际开发中遵循这些最佳实践,写出高质量的Vue3代码。