uni-app中监听网络状态,并在嵌入webView页面的组件中添加网络监测
uni-app中监听网络状态
下载插件
打开网络异常组件页面,点击"下载插件并导入HBuilderX"按钮,打开HBuilderX软件后,选择需要导入插件的项目,点击“确定即可”。
使用插件
<template><view class="content"><mz-network-error @clickFn="hancleClick" message="当前无法连接网络,可检查网络设置是否正常."></mz-network-error></view>
</template>
import mzNetworkError from '@/components/mz-network-error/mz-network-error.vue'
components: {mzNetworkError
},
methods: {hancleClick() {uni.navigateTo({url: 'pages/network/index'});}
}
pages/network/index页面,仿照微信。
<template><view class="main-wrapper"><view class="title">未能连接到互联网</view><view class="subtitle">您的设备未启用移动网络或无线局域网</view><view class="setting-content"><view class="setting-content-title">如需要连接到互联网,请参考以下几点:</view><view class="setting-content-main">检查手机中的无线局域网设置,查看是否有可接入的无线局域网信号。</view><view class="setting-content-main">检查手机是否已接入移动网络,并且手机没有被停机。</view></view><view class="setting-content"><view class="setting-content-title">如果您已接入无线局域网:</view><view class="setting-content-main">请检查您所连接的无线局域网热点是否已接入互联网,或该热点是否已允许您的设备访问互联网。</view></view></view>
</template><script>
</script><style scoped lang="scss">.main-wrapper {padding: 20rpx 40rpx;.title {font-size: 40rpx;height: 100rpx;line-height: 100rpx;font-weight: bolder;}.subtitle {font-size: 28rpx;padding-bottom: 20rpx;margin-bottom: 20rpx;border-bottom: 1px solid rgba(151, 151, 151, 0.15);}.setting-content {.setting-content-title {font-size: 28rpx;margin-bottom: 20rpx;}.setting-content-main {font-size: 28rpx;line-height: 44rpx;padding-left: 60rpx;margin-bottom: 20rpx;position: relative;&::before {content: '';position: absolute;left: 40rpx;top: 20rpx;display: inline-block;width: 10rpx;height: 10rpx;border-radius: 50%;background: #000;}}}}
</style>
效果展示
在嵌入webView页面的组件中添加网络监测
修改网络监测组件mz-network-error
当网络状态发生变化时emit相关事件
created() {this.isNetworkCanUse(usable => {this.show = !usable;this.$emit('networkStatus', this.show);});uni.onNetworkStatusChange(res => {this.show = !res.isConnected;this.$emit('networkStatus', this.show);});
},
修改组件调用
调用网络监测组件mz-network-error 时,绑定networkStatus事件,由于webview会覆盖整个页面,所以需要在监听到网络状态变化时手动修改webview距离顶部的top距离。
<mz-network-error @networkStatus="networkStatusChange" @clickFn="hancleClick"message="当前无法连接网络,可检查网络设置是否正常."></mz-network-error>
<script>import mzNetworkError from '@/components/mz-network-error/mz-network-error.vue'export default {components: {mzNetworkError},data() {return {currentNetworkStatus: true, // true表示网络异常,false表示网络正常webviewUrl: "***",}},watch: {currentNetworkStatus: {handler(newVal) {const top = newVal ? 120 : 64;this.setWebviewTop(top)},deep: true,immediate: true},},methods: {hancleClick() {uni.navigateTo({url: '/pages/network/index'});},networkStatusChange(show) {this.currentNetworkStatus = show},setWebviewTop(top) {// #ifdef APP-PLUSvar currentWebview = this.$scope.$getAppWebview()setTimeout(function() {let wv = currentWebview.children()[0]wv.setStyle({top: top})}, 1000); //如果是页面初始化调用时,需要延时一下// #endif},}}
</script>