NetworkStatus.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <view v-if="isOffline" class="offline-banner">
  3. <text class="offline-icon">📡</text>
  4. <text class="offline-text">网络已断开</text>
  5. </view>
  6. </template>
  7. <script setup lang="ts">
  8. import { ref, onMounted, onUnmounted } from 'vue';
  9. const isOffline = ref(false);
  10. // #ifdef H5
  11. function checkNetworkStatus() {
  12. if (typeof navigator !== 'undefined' && navigator.onLine !== undefined) {
  13. isOffline.value = !navigator.onLine;
  14. }
  15. }
  16. function onOnline() {
  17. isOffline.value = false;
  18. uni.showToast({
  19. title: '网络已恢复',
  20. icon: 'success',
  21. });
  22. }
  23. function onOffline() {
  24. isOffline.value = true;
  25. uni.showToast({
  26. title: '网络已断开',
  27. icon: 'none',
  28. });
  29. }
  30. onMounted(() => {
  31. checkNetworkStatus();
  32. if (typeof window !== 'undefined') {
  33. window.addEventListener('online', onOnline);
  34. window.addEventListener('offline', onOffline);
  35. }
  36. });
  37. onUnmounted(() => {
  38. if (typeof window !== 'undefined') {
  39. window.removeEventListener('online', onOnline);
  40. window.removeEventListener('offline', onOffline);
  41. }
  42. });
  43. // #endif
  44. // #ifndef H5
  45. // App 端使用 uni-app API
  46. onMounted(() => {
  47. uni.onNetworkStatusChange((res) => {
  48. isOffline.value = !res.isConnected;
  49. if (res.isConnected) {
  50. uni.showToast({ title: '网络已恢复', icon: 'success' });
  51. } else {
  52. uni.showToast({ title: '网络已断开', icon: 'none' });
  53. }
  54. });
  55. });
  56. // #endif
  57. </script>
  58. <style scoped>
  59. .offline-banner {
  60. position: fixed;
  61. top: 0;
  62. left: 0;
  63. right: 0;
  64. background: linear-gradient(90deg, #ff6b6b, #ee5a6f);
  65. color: white;
  66. padding: 16rpx 24rpx;
  67. display: flex;
  68. align-items: center;
  69. justify-content: center;
  70. gap: 12rpx;
  71. z-index: 9999;
  72. box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  73. }
  74. .offline-icon {
  75. font-size: 32rpx;
  76. }
  77. .offline-text {
  78. font-size: 28rpx;
  79. font-weight: 500;
  80. }
  81. </style>