1. 组合式 API (Composition API)
Vue 3 引入了 Composition API,它是对 Options API 的补充,提供了更好的逻辑复用和组织方式。
示例:
vue
<script setup>
import { ref, computed, watch } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
watch(count, (newVal) => {
console.log(`Count changed to ${newVal}`)
})
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>
使用
<script setup>
可以简化组件定义,自动暴露顶层绑定给模板使用。
2. 响应式系统的深入理解
reactive()
创建深层响应式对象。shallowReactive()
创建浅层响应式对象。readonly()
和shallowReadonly()
提供只读代理。- 自定义
ref
实现细粒度控制。
示例:自定义 ref
javascript
js
import { customRef } from 'vue'
function useDebouncedRef(value, delay = 200) {
let timeout
return customRef((track, trigger) => {
return {
get() {
track()
return value
},
set(newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
}
}
})
}
3. Teleport 组件
用于将子节点渲染到 DOM 中的不同位置,常用于模态框、通知等全局组件。
示例:
ini
vue
<Teleport to="body">
<div class="modal">This is a modal</div>
</Teleport>
4. Suspense 组件(实验性)
允许你在等待异步组件加载时显示后备内容。
示例:
xml
vue
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
Loading...
</template>
</Suspense>
5. 动态组件与 keep-alive 缓存
使用 <component :is="currentComponent">
动态切换组件,并配合 <keep-alive>
缓存未活动的组件实例。
示例:
ruby
vue
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
6. 插槽 (Slots) 的高级用法
包括具名插槽、作用域插槽以及动态插槽名称。
示例:作用域插槽
xml
vue
<!-- 子组件 -->
<slot :user="currentUser"></slot>
<!-- 父组件 -->
<ChildComponent v-slot="{ user }">
Hello, {{ user.name }}
</ChildComponent>
7. Provide / Inject 跨层级通信
用于祖先组件向其所有子孙后代注入数据,避免逐层传递 props。
示例:
arduino
js
// 祖先组件
provide('theme', 'dark')
// 后代组件
const theme = inject('theme')
8. 自定义指令
创建具有特定行为的自定义 DOM 指令。
示例:
ini
js
const myDirective = {
mounted(el, binding) {
el.style.color = binding.value
}
}
app.directive('color', myDirective)
9. Transition 和 TransitionGroup 动画
为进入/离开 DOM 的元素添加过渡效果。
示例:
ini
vue
<Transition name="fade">
<p v-if="show">Hello</p>
</Transition>
CSS 类:
css
css
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
10. 性能优化技巧
- 使用
v-memo
(Vue 3.2+)缓存复杂计算结果。 - 列表虚拟滚动减少 DOM 渲染压力。
- 合理拆分组件防止不必要的重渲染。
- 使用
markRaw()
避免某些对象被转为响应式。
这些高级特性和语法能够帮助你在开发大型应用时更加得心应手。是否需要针对某个具体功能展开详细说明?