Vue3高级特性详解
1. 组合式API (Composition API)
核心概念
- setup函数是组合式API的入口点
- 响应式系统:ref和reactive
- 生命周期钩子
- 依赖注入:provide/inject
import { ref, onMounted, watch } from 'vue'
export default {
setup() {
// 响应式状态
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
// 方法
const increment = () => {
count.value++
}
// 生命周期钩子
onMounted(() => {
console.log('组件已挂载')
})
// 监听器
watch(count, (newValue, oldValue) => {
console.log(`count从${oldValue}变为${newValue}`)
})
return {
count,
doubleCount,
increment
}
}
}
2. 响应式系统深入
ref vs reactive
// ref用于基本类型
const count = ref(0)
console.log(count.value) // 需要.value访问
// reactive用于对象
const state = reactive({
count: 0,
user: { name: 'John' }
})
console.log(state.count) // 直接访问
常见陷阱
- 解构reactive对象会失去响应性
- ref在模板中自动解包
- 数组和集合的响应式处理
3. 性能优化技巧
1. 合理使用v-memo和v-once
{{ item.name }}
{{ expensiveComputation() }}
2. 异步组件和懒加载
// 异步组件
const AsyncComp = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
)
// 路由懒加载
const routes = [{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
}]
4. 高级组件模式
自定义指令
// 自定义v-focus指令
const vFocus = {
mounted: (el) => el.focus()
}
// 在组件中使用
app.directive('focus', vFocus)
组合式函数(Composables)
// 可复用的鼠标位置跟踪功能
function useMousePosition() {
const x = ref(0)
const y = ref(0)
function update(e) {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => {
window.addEventListener('mousemove', update)
})
onUnmounted(() => {
window.removeEventListener('mousemove', update)
})
return { x, y }
}