Vue errorCaptured 生命周期钩子
实例
使用 errorCaptured 生命周期挂钩捕获来自子组件的错误并向用户创建警报。
<script>export default {errorCaptured() {alert("An error occurred");}}</script>
定义与用法
errorCaptured 当子/子组件中发生错误时,会调用生命周期钩子。
此钩子可用于错误处理、日志记录或向用户显示错误。
当使用 errorCaptured 钩子时,重要的是不要触发错误所在组件的呈现,因为这很可能会导致无限循环。
关于错误的信息在 errorCaptured() 函数中有 3 个参数:
- 错误
- 触发错误的组件
- 错误源类型
发生错误的默认行为是从发生错误的组件传播或 'bubble up'(冒泡)。组件中发生的错误将向上移动到父组件,并继续向上移动,最终在控制台中显示错误消息。
通过运行 return false; 从 errorCaptured() 函数内部,错误不会最终出现在父组件中(停止传播),并且错误也不会最终在控制台中显示为错误消息。错误处理也可以使用 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
使用 errorCaptured 生命周期钩子,返回 return false; 以阻止错误传播。
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 钩子