Hanye官网
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ErrorBoundary.vue 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <template>
  2. <div>
  3. <div v-if="error" class="bg-red-50 border border-red-200 text-red-800 p-4 rounded-md">
  4. <div class="flex items-start">
  5. <div class="flex-shrink-0 mt-0.5">
  6. <svg class="h-5 w-5 text-red-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
  7. <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
  8. </svg>
  9. </div>
  10. <div class="ml-3">
  11. <h3 class="text-sm font-medium">{{ title }}</h3>
  12. <div class="mt-1 text-sm">
  13. <p>{{ errorMessage }}</p>
  14. <button
  15. v-if="retry"
  16. @click="handleRetry"
  17. class="mt-2 px-3 py-1 text-xs font-medium bg-red-100 text-red-800 rounded-md hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
  18. >
  19. {{ retryText }}
  20. </button>
  21. </div>
  22. </div>
  23. </div>
  24. </div>
  25. <slot v-else />
  26. </div>
  27. </template>
  28. <script setup lang="ts">
  29. /**
  30. * 错误边界组件
  31. * 用于捕获和显示组件内部错误
  32. * @prop title - 错误标题
  33. * @prop error - 错误对象
  34. * @prop retry - 是否显示重试按钮
  35. * @prop retryText - 重试按钮文字
  36. * @emit retry - 点击重试按钮时触发
  37. */
  38. import { computed } from 'vue';
  39. const props = defineProps({
  40. title: {
  41. type: String,
  42. default: '发生错误'
  43. },
  44. error: {
  45. type: [Error, Object, null],
  46. default: null
  47. },
  48. retry: {
  49. type: Boolean,
  50. default: false
  51. },
  52. retryText: {
  53. type: String,
  54. default: '重试'
  55. }
  56. });
  57. const emit = defineEmits(['retry']);
  58. /**
  59. * 格式化错误信息
  60. */
  61. const errorMessage = computed(() => {
  62. if (!props.error) return '';
  63. if (props.error instanceof Error) {
  64. return props.error.message;
  65. }
  66. if (typeof props.error === 'object') {
  67. return JSON.stringify(props.error);
  68. }
  69. return String(props.error);
  70. });
  71. /**
  72. * 处理重试操作
  73. */
  74. function handleRetry() {
  75. emit('retry');
  76. }
  77. </script>