【问题标题】:Window is undefined error, when loading node_module package in a component在组件中加载 node_module 包时,窗口未定义错误
【发布时间】:2021-04-13 10:37:44
【问题描述】:

我正在尝试在我的 nuxt.js 应用程序中使用 pickr 包(颜色选择器库),在导入时它提供名为 window is undefined

的错误

代码如下:


<script>
import Pickr from '@simonwep/pickr/dist/pickr.min.js';

let pickr;

export default {
  name: "ColorPicker",
  mounted(){
    pickr = Pickr.create({
          el: '.test-picker',
          theme: 'classic',
          swatches: [
              'rgba(244, 67, 54, 1)',
              'rgba(233, 30, 99, 0.95)',
          ],
  
      });
  }
}
</script>

尝试过的方法

  • 我将pickr 包作为nuxt 插件添加到nuxt.config.jsmode:client
  • 我将pickr 包作为nuxt 插件添加到nuxt.config.jsssr:false

但它没有工作????

【问题讨论】:

    标签: javascript vue.js nuxt.js color-picker


    【解决方案1】:

    经过努力,我想出了这种方法并为我工作

    <script>
    
    let PickrInstance;
    
    if(process.browser){
       PickrInstance = require('@simonwep/pickr/dist/pickr.min.js')
    }
    
    let  pickr;
    
    export default {
      name: "ColorPicker",
      mounted(){
        pickr = PickrInstance.create({
              el: '.test-picker',
              theme: 'classic',
              swatches: [
                  'rgba(244, 67, 54, 1)',
                  'rgba(233, 30, 99, 0.95)',
              ],
    
          });
      }
    }
    </script>
    
    

    【讨论】:

      【解决方案2】:

      您可以尝试将其包装在自定义的 Vue 组件 (VComponent.vue) 中,并在 client-only 标签内渲染该组件

      <client-only>
        <v-component />
      </client-only>
      
      ...
      
      import VComponent from './VComponent';
      
      export default {
        components: { VComponent },
      }
      

      如果仍然抛出错误,您可以尝试动态加载您的自定义组件。而不是import VComponent from './VComponent' 使用:

      const VComponent = () => import('./VComponent');
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 2017-04-01
        • 1970-01-01
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多