uniapp项目实践总结(十一)自定义网络检测组件

导语:很多时候手机设备会突然没网,这时候就需要一个网络检测组件,在没网的时候显示提示用户,提供用户体验。

目录

  • 准备工作
  • 原理分析
  • 组件实现
  • 实战演练
  • 案例展示

准备工作

  • components新建一个q-online文件夹,并新建一个q-online.vue的组件;
  • 按照前一篇所说的页面结构,编写好预定的网络检测页面;

原理分析

主要是使用uni.onNetworkStatusChange来判断网络状态,然后根据状态调整页面样式显示网络提示。

组件实现

准备工作和原理分析完成后,接下来写一个网络检测页面。

模板部分

这里提供了两种提示,一种是全屏显示,一种是顶部显示,支持自定义插槽。

<view class="q-online" v-if="show">
<slot name="content">
<view :class="{'q-online-inner': true, [props.type]: true}">
<q-icon
class="q-online-icon"
:name="props.type == 'top' ? 'info-circle' : 'wifi'"
:size="props.type == 'top' ? 20 : 52"
color="#f30d0d" />
<text class="q-online-txt">您的网络已断开,请检查连接!</text>
</view>
</slot>
</view>

样式部分

.q-online {
.q-online-inner {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100rpx;
background: $netBg;
.q-online-icon {
margin-right: 20rpx;
}
.q-online-txt {
color: $netColor;
font-size: 30rpx;
}
&.full {
position: absolute;
top: 0;
left: 0;
flex-direction: column;
height: 100%;
background: $white;
z-index: 39;
.q-online-txt {
margin-top: 30rpx;
font-size: 36rpx;
}
}
}
}

脚本部分

  • 引入依赖包和属性设置
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
// 页面属性
let show = ref(false);
// 显示类型
const props = defineProps({
type: {
type: String,
default: "top", // top 顶部 full 全屏
},
});
// 状态发送
const emits = defineEmits(["change"]);
  • 方法定义
// 页面方法
// 显示
onLoad((option) => {
checkNet();
});
// 检测网络
function checkNet() {
uni.onNetworkStatusChange((res) => {
const status = res.isConnected;
show.value = !status;
emits("change", status);
let title = status ? "网络已连接!" : "网络已断开!",
icon = status ? "success" : "error";
uni.showToast({
title,
icon,
});
});
}

实战演练

模板使用

<!-- 顶部风格 -->
<q-online type="top" />
<!-- 全屏风格 -->
<q-online type="full" @change="getNetStatus" />

脚本使用

// 获取网络状态
function getNetStatus(val) {
console.log(`网络状态:${val ? "有网" : "无网"}`);
}

案例展示

  • 顶部效果
    在这里插入图片描述
    在这里插入图片描述

  • 全屏效果
    在这里插入图片描述
    在这里插入图片描述

最后

以上就是自定义网络检测组件的主要内容,有不足之处,请多多指正。

posted @   MarkGuan  阅读(272)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示