2

我在我的应用程序中使用 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
4

1 回答 1

3

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

以下对我有用:

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 启动项目中创建):

<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>

我希望这有帮助。

最好的问候,电子手表

于 2020-01-07T11:00:48.007 回答