如何在 gridsome 中添加和使用 vue-confetti

how to add and use vue-confetti in gridsome

我在我的应用程序中使用了 vue-confetti 包,但是它在构建时出现了以下错误,我想知道如何克服这个错误,如何让它只在客户端使用 Gridsome 呈现。

ReferenceError: window is not defined
    at Object.<anonymous> (node_modules/vue-confetti/dist/vue-confetti.js:1:210)
    at __webpack_require__ (webpack/bootstrap:25:0)
    at Module.<anonymous> (assets/js/app.1b103b72.js:43910:20)
    at __webpack_require__ (webpack/bootstrap:25:0)
    at Object.module.exports.module.exports (assets/js/app.1b103b72.js:5973:18)
    at __webpack_require__ (webpack/bootstrap:25:0)
    at assets/js/app.1b103b72.js:118:18
    at Object.<anonymous> (assets/js/app.1b103b72.js:121:10)
    at o (D:\angular\climber-website\node_modules\vue-server-renderer\build.prod.js:1:77543)
    at D:\angular\climber-website\node_modules\vue-server-renderer\build.prod.js:1:78136```


  [1]: https://www.npmjs.com/package/vue-confetti

我找到了解决您问题的方法,以下链接对我有帮助:

以下对我有用:

main.js(在 gridsome 启动项目中默认创建)

// This is the main.js file. Import global CSS and scripts here.
// The Client API can be used here. Learn more: gridsome.org/docs/client-api

import DefaultLayout from '~/layouts/Default.vue'

export default function (Vue, { router, head, isClient }) {
  // Set default layout as a global component
  Vue.component('Layout', DefaultLayout)
  if(process.isClient) {
    const confetti = require('vue-confetti').default
    Vue.use(confetti)
  }
}

应该显示五彩纸屑的页面如下所示(我采用了默认的 About.vue,它已经存在于一个新的 gridsome 启动项目中):

About.vue(在gridsome starter项目中默认创建):

<template>
  <Layout>
    <h1>About us</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error doloremque omnis animi, eligendi magni a voluptatum, vitae, consequuntur rerum illum odit fugit assumenda rem dolores inventore iste reprehenderit maxime! Iusto.</p>
    <button @click="start">Start</button>
    <button @click="stop">Stop</button>
    <button @click="love">Show some love</button>
  </Layout>
</template>

<script>

export default {
  metaInfo: {
    title: 'About us'
  },
  methods: {
      start() {
        this.$confetti.start();
      },

      stop() {
        this.$confetti.stop();
      },

      love() {
        this.$confetti.update({
          particles: [
            {
              type: 'heart',
            },
            {
              type: 'circle',
            },
          ],
          defaultColors: [
            'red',
            'pink',
            '#ba0000'
          ],
        });
      }
    }
}
</script>

希望对您有所帮助。

此致, 电子手表