一、Vue 3 新增特性
1. Composition API
- 概述:
- Composition API 提供了一种更灵活和强大的方式来组织和复用逻辑。
- 适用于复杂组件和逻辑复用场景。
- 主要功能:
setup
函数:组件的入口点,用于定义响应式数据、方法、生命周期钩子等。- 响应式 API:
ref
和reactive
提供更细粒度的响应式控制。 - 生命周期钩子:
onMounted
、onUnmounted
等新生命周期钩子。 - 计算属性和监听器:
computed
和watch
的 Composition API 版本。
- 示例:
<template> <div> <p>{ { count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { ref, onMounted } from 'vue'; export default { setup() { const count = ref(0); const increment = () => { count.value++; }; onMounted(() => { console.log('Component mounted'); }); return { count, increment }; } }; </script>
2. Teleport
- 概述:
Teleport
允许将组件的内容渲染到 DOM 中的其他位置,而不改变组件的逻辑结构。
- 用途:
- 适用于模态框、提示框等需要脱离当前组件树的场景。
- 示例:
<template> <button @click="showModal = true">Open Modal</button> <teleport to="body"> <div v-if="showModal" class="modal"> <p>This is a modal!</p> <button @click="showModal = false">Close</button> </div> </teleport> </template> <script> import { ref } from 'vue'; export default { setup() { const showModal = ref(false); return { showModal }; } }; </script> <style> .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; pad