当前位置:   article > 正文

如何使用Vue 3和Type Script进行组件化设计

如何使用Vue 3和Type Script进行组件化设计

Vue 3中,Composition API 是一种全新的逻辑复用和代码组织方式,它允许你将组件的逻辑(如响应式状态、计算属性、方法、生命周期钩子等)封装到单独的函数中,从而提高了代码的可复用性和可维护性。以下是如何在Vue 3中使用Composition API的基本步骤:

1. 引入必要的函数

首先,你需要从 vue 包中引入 defineComponent 和 Composition API 的其他函数(如 refreactivecomputedwatchonMounted 等)。defineComponent 是可选的,但它提供了类型推断和一些额外的运行时检查。

  1. import {
  2. defineComponent, ref, computed, onMounted } from 'vue';

2. 使用 setup 函数

setup 函数是 Composition API 的入口点。它是一个在组件创建之前被调用的同步函数,用于设置组件的响应式状态、计算属性、方法等。setup 函数会在 beforeCreate 和 created 生命周期钩子之前被调用,并且它是 this 的上下文之外的(即 this 在 setup 中不是组件实例)。

  1. <script setup lang="ts">
  2. import { ref, computed, onMounted } from 'vue';
  3. const count = ref(0);
  4. const doubled = computed(() => count.value * 2);
  5. onMounted(() => {
  6. console.log('Component is mounted!');
  7. });
  8. function increment() {
  9. count.value++;
  10. }
  11. </script>

注意:<script setup> 是 Vue 3 引入的语法糖,它提供了一种更简洁的方式来使用 Composition API。它会自动将 setup 函数的返回值暴露给模板,并且你不需要显式地调用 defineComponent

3. 在模板中使用

在模板中,你可以直接访问 setup 函数中返回的任何响应式状态、计算属性或方法。

  1. <template>
  2. <div>
  3. <p>{
  4. { count }}</p>
  5. <p>{
  6. { doubled }}</p>
  7. <button @click="increment">Increment</button>
  8. </div>
  9. </template>

4. 响应式状态

使用 ref 或 reactive 来创建响应式状态。ref 用于基本数据类型,而 reactive 用于对象或数组。

  1. const count = ref(0); // 使用 ref 创建响应式的基本数据类型
  2. const person = reactive({
  3. name: 'Alice', age: 30 }); // 使用 reactive 创建响应式的对象

5. 生命周期钩子

Composition API 提供了与组件生命周期钩子对应的函数,如 onMountedonUpdatedonUnmounted 等。

  1. onMounted(() => {
  2. // 组件挂载后执行的代码
  3. });
  4. onUpdated(() => {
  5. // 组件更新后执行的代码
  6. });
  7. onUnmounted(() => {
  8. // 组件卸载后执行的代码
  9. });

6. 依赖注入和提供/注入

虽然 Composition API 本身不直接提供类似于 provide 和 inject 的API,但你可以通过 setup 函数的第二个参数(context)来访问 provide 和 inject。不过,更常见的做法是使用 Vue 3 提供的 provide 和 inject 函数(这些函数不是 setup 特有的,但可以在 setup 中使用)。

  1. // 父组件
  2. setup() {
  3. const theme = ref('dark');
  4. provide('theme', theme);
  5. // ...
  6. }
  7. // 子组件
  8. setup(props, {
  9. inject }) {
  10. const theme = inject('theme')!; // 注意:需要类型断言或使用可选链来处理可能的undefined
  11. // ...
  12. }
  13. // 或者使用独立的 provide 和 inject 函数
  14. // setup() {
  15. // const theme = ref('dark');
  16. // provide('theme', theme);
  17. // // ...
  18. // }
  19. // setup(props, context) {
  20. // const theme = inject('theme', 'default-theme'); // 第二个参数是默认值
  21. // // ...
  22. // }

请注意,上面的 inject 示例中使用了 ! 来进行非空断言,这是因为 TypeScript 无法自动推断 inject 返回值的非空性。如果你不确定注入的值是否存在,你应该使用可选链(?.)或默认值来处理它。

通过以上步骤,你可以在Vue 3中有效地使用Composition API来构建你的组件。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/1021716
推荐阅读
相关标签
  

闽ICP备14008679号