生命周期钩子onErrorCaptured

如何使用 onErrorCaptured() 捕获组件树中的错误。

实践步骤

  • 创建一个父组件 ParentComponent,它包含一个子组件 ChildComponent
  • ChildComponent 中故意抛出一个错误。
  • ParentComponent 使用 onErrorCaptured() 捕获子组件中的错误,并进行相应的处理。

代码实现

<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent />
    <p v-if="errorMessage">Error caught: {{ errorMessage }}</p>
  </div>
</template>

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

// 引入子组件
import ChildComponent from './ChildComponent.vue';

// 定义错误信息的引用
const errorMessage = ref<string | null>(null);

// 捕获子组件中的错误
onErrorCaptured((err, instance, info) => {
  console.error('Captured error:', err);
  console.log('Error source:', instance);
  console.log('Error info:', info);

  // 处理错误信息
  errorMessage.value = (err as Error).message;
  return false; // 返回 false 以继续向上传递错误,返回 true 则会停止错误的传播
});
</script>
<!-- ChildComponent.vue -->
<template>
  <div>
    <h2>Child Component</h2>
    <button @click="throwError">Throw Error</button>
  </div>
</template>

<script lang="ts" setup>
function throwError() {
  throw new Error('This is an intentional error from ChildComponent');
}
</script>

解释

  1. ParentComponent.vue

    • 使用 onErrorCaptured 钩子捕获 ChildComponent 中抛出的错误。
    • 当错误被捕获时,错误信息会被记录在 errorMessage 中,并显示在模板中。
  2. ChildComponent.vue

    • 定义一个 throwError 函数,当点击按钮时抛出一个错误。

使用方式

ParentComponent.vueChildComponent.vue 放在项目的合适位置(例如 components 文件夹下),并在应用中引用 ParentComponent.vue 来查看效果。

这样,当子组件中发生错误时,父组件会捕获到该错误,并可以根据需求做出相应的处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vinca@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值