Vue Router History Mode with PWA in Offline Mode

前端 未结 2 1387
你的背包
你的背包 2021-02-04 11:36

To get history mode working with Vue-Router you need to return the contents of your main page when trying to access a route that doesn\'t exist. For example when you visit

相关标签:
2条回答
  • 2021-02-04 11:51

    You need to set the navigateFallback option in your vue.config.js file:

    pwa: {
      workboxOptions: {
        navigateFallback: 'index.html'
      }
    }
    

    It will automatically add the necessary code to your service worker:

    workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("index.html"));
    

    I had the same problem and I found the solution here: https://github.com/vuejs/vue-cli/issues/717#issuecomment-382079361

    0 讨论(0)
  • 2021-02-04 11:52

    If your site is a single page app, you can use a NavigationRoute to return a specific response for all navigation requests.

    workbox.routing.registerNavigationRoute('/single-page-app.html')
    

    In my case in vue :

    workbox.routing.registerNavigationRoute('/index.html')
    

    Whenever a user goes to your site in the browser, the request for the page will be a navigation request and will be served the cached page /single-page-app.html.

    Note: You should have the page cached via workbox-precaching or through your own installation step).

    By default, this will respond to all navigation requests, if you want to restrict it to respond to a subset of URL’s you can use the whitelist and blacklist options to restrict which pages will match this route.

    Update: Workbox V5

    const handler = workbox.precaching.createHandlerBoundToURL("/index.html");
    
    const navigationRoute = new workbox.routing.NavigationRoute(handler);
    
    workbox.routing.registerRoute(navigationRoute);
    
    0 讨论(0)
提交回复
热议问题