0

我已经阅读了关于堆栈溢出的所有其他帖子(其中有很多)。但据我所知,它们都提供了相同的潜在修复,例如if(process.client)用. 不幸的是,这些解决方案都不适合我。似乎包文件(flickity.js)仍在服务器端运行,导致错误。我尝试用require替换导入并将其包装在条件中,但这也不起作用。如您所料,如果我不包含该行,我得到的错误是. 当我按如下方式包含它时,我得到<client-only>mode:"client"clientnuxt.config.jsif (process.client)import Flickity from 'flickity';Flickity is undefinedwindow is not defined - flickity.js 有谁知道防止这个包运行我错过的服务器端的任何其他要求?

使用 flickity 的组件(包装在仅客户端标签中)

<script>

        import Flickity from 'flickity'; // I have tried removing this having been told that Nuxt automatically imports all plugins. But it didn't work and rendered a Flickity is undefined error

        


        export default {
            created() {  
                
            },
            props: {
                images: {
                    required:true,
                    type:Array
                }
            },
            mounted() {
                this.initiateCarousel();

            },
            methods: {
                initiateCarousel() {
                    if (process.client) {
                        const gallery = this.$refs.gallery;
                        const carousel = this.$refs.carousel;
                        console.log(carousel)
                        var flkty = new Flickity( carousel , {
                            cellAlign: 'left',
                            lazyLoad: 3,
                            contain: true,
                            pageDots: false,
                            prevNextButtons: false
                        });
                    }
                }
            },
        }
    </script>

nuxt.config.js 中的插件数组

plugins: [
  '~/plugins/flexboxgrid/index',
  '~/plugins/flickity.client'

],

~plugins 目录中的 Flickity.client.js 文件

import Flickity from 'flickity'; 

(我也尝试添加export default Flickity;到此文件,但呈现相同的服务器错误

4

1 回答 1

4

使用 nuxt 插件,您将在每个页面上导入 Flickity。

另一种方法是使用, 并且仅针对事件的当前 nuxt 页面进行动态导入,如下所示:Flickityawait importmounted

async mounted() {
   await this.initiateCarousel();
},
methods: {
  async initiateCarousel() {
    if (process.client) {
        const gallery = this.$refs.gallery;
        const carousel = this.$refs.carousel;
        console.log(carousel);

        const { default: Flickity } = await import(/* webpackChunkName: "flickity" */ 'Flickity');

        var flkty = new Flickity( carousel , {
            cellAlign: 'left',
            lazyLoad: 3,
            contain: true,
            pageDots: false,
            prevNextButtons: false
        });
    }
  }
}
于 2021-01-21T21:46:34.453 回答