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>