gpt4 book ai didi

vue.js - 如何从 registerServiceWorker.js 调用 Vue 应用程序 $refs.components 或 Vuex $store 中的方法?

转载 作者:行者123 更新时间:2023-12-03 19:15:43 25 4
gpt4 key购买 nike

我正在研究使用 Vue CLI 搭建的 Vue PWA,默认情况下使用 register-service-worker用于在 registerServiceWorker.js 中公开 serviceWorker 生命周期方法的包:

ready () {
console.log(
'App is being served from cache by a service worker.'
)
},
registered () {
console.log('Service worker has been registered.')
},
cached () {
console.log('Content has been cached for offline use.')
},
updatefound () {
console.log('New content is downloading.')
},
updated () {
console.log('New content is available; please refresh.')
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
registerServiceWorker.js导入到 main.js :

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'
import './registerServiceWorker'

Vue.config.productionTip = false

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

问题是,我如何访问范围以从 registerServiceWorker.js 的范围内调用我的 Vuex $store 或 App.vue $refs.components 中的方法,例如

updated () {
// Something like
this.$store.commit('showUpdateNotification')
// OR
this.$refs.updateNotification.show()
}

我知道我可以在我的应用程序中设置额外的 eventListeners 来做到这一点,但似乎更好地利用 registerServiceWorker.js ?

最佳答案

在您的 registerServiceWorker.js 中导入 Vuex 商店文件。

IE。

/* eslint-disable no-console */

import { register } from 'register-service-worker'
import appConfig from './app.config.json'
import store from './store'

if (process.env.NODE_ENV === 'production') {
register(`${appConfig.router.baseUrl}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.'
)
},
cached() {
console.log('Content has been cached for offline use.')
},
updated() {
console.log('New content is available; please refresh.')
store.commit('showUpdateNotification')
},
offline() {
console.log(
'No internet connection found. App is running in offline mode.'
)
},
error(error) {
console.error('Error during service worker registration:', error)
},
})
}

关于vue.js - 如何从 registerServiceWorker.js 调用 Vue 应用程序 $refs.components 或 Vuex $store 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com