我有一个VueJs / Ionic4 / Capacitor应用。我要尝试的是侦听网络何时脱机并显示警报。基于电容器docs和this git repo,我有以下代码。如果您尝试导航到新屏幕,这将显示警报。 我如何监听此networkStatusChange,以便设备离线后显示警报?我尝试使用IonicVuePage组件中的created和mount。也许这应该在App.vue中发生?
main.js
import Vue from 'vue';
import App from './App.vue';
import Ionic from '@ionic/vue';
import VueRouter from 'vue-router';
// Capacitor
import { Plugins } from '@capacitor/core';
const { Network } = Plugins;
// Routing
import router from './router';
// Ionic and common css
import '@ionic/core/css/ionic.bundle.css';
import '@ionic/core/css/core.css';
import './theme/common.css';
// Components
import IonicVuePage from './components/IonicVuePage';
Vue.config.productionTip = false;
Vue.config.ignoredElements = [/^ion-/];
Vue.use(VueRouter);
Vue.use(Ionic);
// Initialize Capacitor
initCapacitor();
// Register as global component to be used as a boilerplate
Vue.component('IonicVuePage', IonicVuePage);
new Vue({
router,
render: h => h(App),
}).$mount('#app');
// Initial Capacitor calls
async function initCapacitor() {
// Set network checks
Network.getStatus()
.then(status => {
(Vue.prototype.$networkStatus = status);
})
.catch(error => {
console.log(error);
});
// Listen to network changes
Network.addListener('networkStatusChange', status => {
(Vue.prototype.$networkStatus = status);
});
}
components / IonicVuePage.vue
<template>
<ion-page class="ion-page" main>
<ion-header>
<ion-toolbar color="primary">
<ion-title>{{ title }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-content">
<slot />
</ion-content>
</ion-page>
</template>
<script>
import network from "@/mixins/network";
export default {
name: "IonicVuePage",
mixins: [network],
props: {
title: { type: String, default: "" }
},
created() {
if (!this.checkNetworkStatus()) {
return this.showNetworkAlert();
}
}
};
</script>
mixins / network.js
export default {
methods: {
checkNetworkStatus() {
if (this.$networkStatus) {
return this.$networkStatus && this.$networkStatus.connected;
}
else {
return true;
}
},
showNetworkAlert() {
return this.$ionic.alertController
.create({
header: 'No internet connection',
message: 'Please check your internet connection.',
buttons: ['OK'],
})
.then(a => a.present());
},
},
}