Vue 'errorCaptured' 生命周期钩子
示例
使用 errorCaptured
生命周期钩子来捕获子组件的错误并向用户创建警报。
<script>
export default {
errorCaptured() {
alert("An error occurred");
}
}
</script>
运行示例 »
更多示例请参见下方。
定义和用法
当子/后代组件发生错误时,会调用 errorCaptured
生命周期钩子。
此钩子可用于错误处理、日志记录或向用户显示错误。
使用 errorCaptured
钩子时,重要的是不要触发发生错误的组件的渲染,因为这很可能会导致无限循环。
有关错误的详细信息可在 errorCaptured()
函数的三个参数中获取
- 错误
- 触发错误的组件
- 错误源类型
发生错误的默认行为是传播或“冒泡”到发生错误组件的父组件。组件中发生的错误会向上移动到父组件,并继续向上移动,最终在控制台中显示为错误消息。
通过在 errorCaptured()
函数中运行 return false;
,错误将不会进入父组件(停止传播),错误也不会在控制台中显示为错误消息。
还可以使用 app.config.errorHandler
函数设置错误处理。
更多示例
示例 1
使用 errorCaptured
生命周期钩子捕获错误并将错误信息写入控制台。
App.vue
:
<template>
<h1>The 'errorCaptured' Lifecycle Hook</h1>
<p>Whenever there is an error in a child component, the errorCaptured() function is called on the parent.</p>
<p>Open the browser console to see the captured error details.</p>
<div>
<comp-one></comp-one>
</div>
</template>
<script>
export default {
errorCaptured(error,compInst,errorInfo) {
console.log("error: ", error);
console.log("compInst: ", compInst);
console.log("errorInfo: ", errorInfo);
}
}
</script>
<style>
#app > div {
border: dashed black 1px;
border-radius: 10px;
padding: 10px;
margin-top: 10px;
background-color: lightgreen;
}
</style>
ComOne.vue
:
<template>
<h2>Component</h2>
<p>This is the component</p>
<button @click="generateError">Generate Error</button>
</template>
<script>
export default {
methods: {
generateError() {
this.$refs.objEl.innerHTML = "hi";
}
}
}
</script>
运行示例 »
示例 2
使用带有 return false;
的 errorCaptured
生命周期钩子来阻止错误传播。
App.vue
:
<template>
<h1>The 'errorCaptured' Lifecycle Hook</h1>
<p>Whenever there is an error in a child component, the errorCaptured() function is called on the parent.</p>
<p>Open the browser console to see the captured error details.</p>
<div>
<comp-one></comp-one>
</div>
</template>
<script>
export default {
errorCaptured(error,compInst,errorInfo) {
console.log("error: ", error);
console.log("compInst: ", compInst);
console.log("errorInfo: ", errorInfo);
return false;
}
}
</script>
<style>
#app > div {
border: dashed black 1px;
border-radius: 10px;
padding: 10px;
margin-top: 10px;
background-color: lightgreen;
}
</style>
ComOne.vue
:
<template>
<h2>Component</h2>
<p>This is the component</p>
<button @click="generateError">Generate Error</button>
</template>
<script>
export default {
methods: {
generateError() {
this.$refs.objEl.innerHTML = "hi";
}
}
}
</script>
运行示例 »
相关页面
Vue 教程:Vue 生命周期钩子
Vue 教程:'errorCaptured' 钩子