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' 鉤子