如何使用 vuejs 制作可安装的 PWA?

Ale*_*ter 5 vue.js progressive-web-apps vuejs2

我想使用按钮通过 chrome/firefox 安装我的 vue 应用程序(显示 pwa 安装提示)

<button @click="install">install</button>

var deferredPrompt
methods: {
  install() {
      deferredPrompt.prompt()
      deferredPrompt.userChoice.then((choiceResult) => {
          if (choiceResult.outcome === 'accepted') {
              console.log('User accepted the A2HS prompt')
          } else {
              console.log('User dismissed the A2HS prompt')
          }
          deferredPrompt = null
      })  
  }    
}
Run Code Online (Sandbox Code Playgroud)

一旦我构建了应用程序及其在线,我单击按钮并在控制台上获得 deferredPrompt null。 我缺少什么?

错误

Pet*_*eLe 5

看起来您beforeinstallpromptwindow对象上没有事件侦听器。

在 vuejs 中,您需要在created()事件中执行此操作,例如:

export default {
  name: "App",
  data() {
    return {
      deferredPrompt: null
    };
  },
  created() {
    window.addEventListener("beforeinstallprompt", (e) => {
      e.preventDefault();
      // Stash the event so it can be triggered later.
      this.deferredPrompt = e;
    });
  },
  methods: {
    async install() {
      this.deferredPrompt.prompt();
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

此外,您应该只在beforeinstallprompt事件被触发和deferredPrompt设置时才显示安装按钮。否则,按钮将可见但不执行任何操作。

查看https://medium.com/js-dojo/promoting-your-vue-js-pwa-installation-6bd112342c19了解更多详情。