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

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

1. 引入必要的函数

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

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

2. 使用 setup 函数

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

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

const count = ref(0);
const doubled = computed(() => count.value * 2);

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

function increment() {
  count.value++;
}
</script>

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

3. 在模板中使用

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

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

4. 响应式状态

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

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

5. 生命周期钩子

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

onMounted(() => {
   
  // 组件挂载后执行的代码
});

onUpdated(() => {
   
  // 组件更新后执行的代码
});

onUnmounted(() => {
   
  // 组件卸载后执行的代码
});

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

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

// 父组件
setup() {
   
  const theme = ref('dark');
  provide('theme', theme);
  // ...
}

// 子组件
setup(props, {
    inject }) {
   
  const theme = inject('theme')!; // 注意:需要类型断言或使用可选链来处理可能的undefined
  // ...
}

// 或者使用独立的 provide 和 inject 函数
// setup() {
   
//   const theme = ref('dark');
//   provide('theme', theme);
//   // ...
// }

// setup(props, context) {
   
//   const theme = inject('theme', 'default-theme'); // 第二个参数是默认值
//   // ...
// }

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值