Skip to content

13.你知道哪些 Vue3 新特性?

  • Composition API

    • 使用函数的方式编写 vue 组件。
    • 组合式 API (响应式 API ref()、reactive(),生命周期钩子onMounted()、onUnmounted(),依赖注入inject()、provide())
    • 组合式 API 并不是函数式编程。
  • SFC Composition API Syntax Sugar (<script setup>)

    • 单文件组合式 API 语法糖(setup 语法糖)
    • 让代码更简洁,性能更好(不需要借助代理对象)。
  • Teleport

    • 类似于 React 中的 Portal 传送门组件,指定将组件渲染到某个容器中。
    • 经常用于处理弹窗组件和模态框组件。
    vue
    <button @click="open = true">打开模态框</button>
    <Teleport to="body">
      <div v-if="open" class="modal">
        <button @click="open = false">关闭</button>
      </div>
    </Teleport>
    <button @click="open = true">打开模态框</button>
    <Teleport to="body">
      <div v-if="open" class="modal">
        <button @click="open = false">关闭</button>
      </div>
    </Teleport>
  • Fragments

    • Fragment(片段)Vue3 中允许组件中包含多个节点。无需引入额外的 DOM 元素。
  • Emits Component Option

    • Vue3 中默认绑定的事件会被绑定到根元素上。通过 Emits 属性可将事件从attrs 中移除。
  • createRenderer API from @vue/runtime-core to create custom renderers

    • 提供自定义渲染器,可以在非 DOM 环境中使用 Vue 的运行时。
  • SFC State-driven CSS Variables (v-bind in <style>)

    • 在 css 中使用 v-bind 绑定样式
    scss
    background: v-bind(color);
    background: v-bind(color);
  • SFC <style scoped> can now include global rules or rules that target only slotted content

    • 在作用域样式中可以包含全局规则或只针对插槽内容的规则
    scss
    /* 跨组件修改组件内样式 */
    .parent :deep(h1) {
      color: red;
    }
    /* 控制全局样式 */
    :global(.root) {
      width: 100px;
      height: 100px;
      background: yellow;
    }
    /* 控制插槽内容的样式 */
    :slotted(.child) {
      color: red;
    }
    /* 跨组件修改组件内样式 */
    .parent :deep(h1) {
      color: red;
    }
    /* 控制全局样式 */
    :global(.root) {
      width: 100px;
      height: 100px;
      background: yellow;
    }
    /* 控制插槽内容的样式 */
    :slotted(.child) {
      color: red;
    }
  • Suspense experimental

    • 主要的作用优雅地处理异步组件的加载状态
    vue
    <Suspense>
        <template #default>
            <!-- 可以配合async setup使用 -->
            <AsyncComponent></AsyncComponent>
        </template>
        <template #fallback>
            正在加载异步组件...
        </template>
    </Suspense>
    <Suspense>
        <template #default>
            <!-- 可以配合async setup使用 -->
            <AsyncComponent></AsyncComponent>
        </template>
        <template #fallback>
            正在加载异步组件...
        </template>
    </Suspense>

参考文档:Vue3 迁移指南

Released under the MIT License.