Vue 3 + TypeScript 实现父子组件协同工作案例解析

引言

        在现代的前端开发中,Vue.js 作为一款流行的渐进式 JavaScript 框架,为我们构建交互式用户界面提供了强大的支持。Vue 3 的推出带来了许多新特性,尤其是组合式 API 的引入,让代码的组织和复用更加灵活。同时,TypeScript 的使用也为 Vue 项目带来了静态类型检查的优势,提高了代码的可维护性和健壮性。本文将通过一个具体的案例,展示如何在 Vue 3 中使用 TypeScript 实现父子组件的协同工作,并运用一些推荐的特性,如 setuprefcomputedwatchemits 等。

项目结构

        首先,我们来看一下项目的基本结构:

src
├── components
│   ├── ParentComponent.vue
│   └── ChildComponent.vue
└── main.ts

代码实现

ParentComponent.vue

<template>
  <div>
    <h1>Parent Component</h1>
    <p>Count In Parent:{
  
  {count}}</p>
    <button @click="incrementParentCount">Increment Parent Count</button>
    <ChildComponent :initialCount="count" @child-count-updated="updateParentCount" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default defineComponent({
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    // 使用 ref 创建响应式数据
    const count = ref<number>(0);

    // 父组件的方法,用于增加计数
    const incrementParentCount = () => {
      count.value++;
    };

    // 处理子组件触发的事件
    const updateParentCount = (newCount: number) => {
      count.value = newCount;
    };

    return {
      count,
      incrementParentCount,
      updateParentCount
    };
  }
});
</script>

         在 ParentComponent.vue 中,我们使用 defineComponent 定义组件。通过 ref 创建了一个响应式的 count 变量,用于存储父组件的计数。incrementParentCount 方法用于增加父组件的计数。同时,我们监听了子组件触发的 child-count-updated 事件,并在 updateParentCount 方法中更新父组件的计数。

ChildComponent.vue

<template>
  <div>
    <h2>Child Component</h2>
    <p>Count in Child: {
  
  { childCount }}</p>
    <button @click="incrementChildCount">Increment Child Count</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, PropType } from 'vue';

export default defineComponent({
  name: 'ChildComponent',
  props: {
    initialCount: {
      type: Number as PropType<number>,
      required: true
    }
  },
  emits: ['child-count-updated'],
  setup(props, { emit }) {
    // 使用 ref 创建响应式数据,初始值来自父组件的 props
    const childCount = ref<number>(props.initialCount);

    // 计算属性,计算子组件计数的两倍
    const doubleCount = computed(() => childCount.value * 2);

    // 监听子组件计数的变化,并触发事件通知父组件
    watch(childCount, (newValue) => {
      emit('child-count-updated', newValue);
    });

    // 子组件的方法,用于增加计数
    const incrementChildCount = () => {
      childCount.value++;
    };

    return {
      childCount,
      doubleCount,
      incrementChildCount
    };
  }
});
</script>

         在 ChildComponent.vue 中,我们接收父组件传递的 initialCount 作为 props。使用 ref 创建了一个响应式的 childCount 变量,其初始值为 props.initialCount。通过 computed 定义了一个计算属性 doubleCount,用于计算子组件计数的两倍。使用 watch 监听 childCount 的变化,当计数发生变化时,触发 child-count-updated 事件通知父组件。incrementChildCount 方法用于增加子组件的计数。

main.ts

import { createApp } from 'vue';
import ParentComponent from './components/ParentComponent.vue';

//使用 createApp 函数创建了一个 Vue 应用实例,并将 ParentComponent 作为根组件传递给它。
const app = createApp(ParentComponent);
//创建的 Vue 应用实例挂载到 DOM 中的指定元素上,从而使 Vue 应用开始运行并渲染到页面上。
app.mount('#app');

        在 main.ts 中,我们创建了 Vue 应用实例,并将 ParentComponent 挂载到 DOM 中的 #app 元素上。

解释与总结

  • 响应式数据管理:通过 ref 创建响应式数据,使得数据的变化能够自动触发视图的更新。
  • 计算属性computed 用于创建计算属性,它会根据依赖的响应式数据的变化而自动更新,避免了不必要的重复计算。
  • 监听数据变化watch 可以监听响应式数据的变化,并在变化时执行相应的回调函数,方便我们在数据变化时进行一些额外的操作。
  • 父子组件通信:父组件通过 props 向子组件传递数据,子组件通过 emit 触发事件向父组件传递数据,实现了父子组件之间的双向通信。

        通过这个案例,我们可以看到 Vue 3 的组合式 API 和 TypeScript 的结合使用,让代码更加清晰、可维护,同时也能充分发挥 Vue 3 的新特性。希望本文对你理解 Vue 3 中的父子组件协同工作有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值