Vue 3 新特性及新 API 详解
Vue 3 新特性及新 API 详解

Vue 3 于 2020 年正式发布,带来了许多新特性和改进,使其更强大、更灵活,同时保留了 Vue 2 的易用性和开发体验。本文将详细介绍 Vue 3 的新特性及新 API,帮助开发者更好地理解和应用这些新功能。

1. Composition API

Composition API 是 Vue 3 中最重要的新增功能之一。它提供了一种更灵活和可组合的方式来编写组件逻辑,特别是在处理复杂逻辑时,比 Options API 更为方便。

<script setup>
import { ref } from 'vue';

const count = ref(0);
const increment = () => {
  count.value++;
};
</script>

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

在上面的示例中,我们使用了 ref 来声明一个响应式变量 count,并定义了一个方法 increment 来修改该变量。

2. Teleport

Teleport 是 Vue 3 中新增的一个功能,允许将组件的渲染输出移动到 DOM 中的其他位置。这对于模态框、通知等需要脱离组件树的 UI 元素非常有用。

<template>
  <div>
    <button @click="showModal = true">Show 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>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const showModal = ref(false);
</script>

在这个例子中,模态框的 HTML 被移动到了 body 元素中,而不是默认的组件父元素。

3. Fragments

Vue 3 支持 Fragment,这意味着组件可以返回多个根元素,而不再需要被包裹在一个单一的根元素中。

<template>
  <div>First element</div>
  <div>Second element</div>
</template>

这种特性在不需要额外的包裹元素时非常有用,减少了不必要的 DOM 层级。

4. Emits Option

在 Vue 3 中,可以通过 emits 选项显式声明组件可以触发的事件。这提高了代码的可读性和维护性,并且在开发模式下有助于捕获未声明的事件。

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['update']);

const updateValue = () => {
  emit('update', 'newValue');
};
</script>

<template>
  <button @click="updateValue">Update</button>
</template>

在这个示例中,我们使用 defineEmits 明确声明了组件将触发 update 事件。

5. Suspense

Suspense 是 Vue 3 中新增的一个特性,允许在异步组件加载时显示一个加载状态。它对异步数据加载和代码分割非常有用。

<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template>

<script setup>
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
);
</script>

在这个示例中,当 AsyncComponent 加载时,将显示 "Loading..."。

6. v-model 的多绑定

在 Vue 3 中,v-model 支持多个绑定。这意味着你可以在同一个组件中使用多个 v-model 进行双向绑定。

<script setup>
const firstName = ref('');
const lastName = ref('');
</script>

<template>
  <CustomInput v-model:firstName="firstName" v-model:lastName="lastName" />
</template>

在这个示例中,我们使用了两个 v-model 绑定来分别处理 firstNamelastName

7. 全局 API 变化

Vue 3 对全局 API 进行了重构,现在可以更灵活地配置应用。

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

const app = createApp(App);

app.use(router);
app.use(store);

app.mount('#app');

通过 createApp 创建应用实例,可以更方便地进行插件和路由等全局配置。

8. Tree-shaking

Vue 3 的构建工具支持 tree-shaking,这意味着未使用的代码会在构建过程中被移除,从而减小打包后的文件大小。

// 仅引入需要的功能,避免不必要的代码引入
import { createApp } from 'vue';
import { createRouter } from 'vue-router';
import App from './App.vue';

const app = createApp(App);
const router = createRouter({ /* routes */ });

app.use(router);
app.mount('#app');

通过这种方式,只引入实际使用的功能,可以有效减小最终打包的体积。

9. Composition API 中的生命周期钩子

在 Composition API 中,Vue 3 提供了等效于 Options API 的生命周期钩子。

<script setup>
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  console.log('Component mounted');
});

onUnmounted(() => {
  console.log('Component unmounted');
});
</script>

这种方式使得在使用 Composition API 时,仍然可以方便地使用生命周期钩子。

10. 更好的 TypeScript 支持

Vue 3 从设计之初就更加关注 TypeScript 的支持,使得在 Vue 项目中使用 TypeScript 更加顺畅。

<script setup lang="ts">
import { ref } from 'vue';

const count = ref<number>(0);

const increment = (): void => {
  count.value++;
};
</script>

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

在这个示例中,我们使用了 TypeScript 的类型注解,使得代码更加类型安全。

11. Custom Directives

Vue 3 提供了更灵活的自定义指令定义方式。

const app = createApp({});

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

这种方式使得定义自定义指令更加简单和直观。

12. 新的响应式系统

Vue 3 的响应式系统进行了重构,性能更高,同时支持更加灵活的响应式数据操作。

import { reactive, effect } from 'vue';

const state = reactive({
  count: 0
});

effect(() => {
  console.log(`Count is: ${state.count}`);
});

state.count++;

新的响应式系统提供了更高的性能和灵活性,使得开发更为高效。

总结

Vue 3 带来了许多新的特性和改进,使得开发更为灵活和高效。从 Composition API 到 Teleport,再到 Suspense 和多个 v-model 绑定,这些新功能增强了 Vue 的功能和灵活性,同时保持了其简单易用的特点。希望通过本文的介绍,能帮助你更好地掌握 Vue 3 的新特性和 API,提高开发效率。