窗口未定义错误,在组件中加载 node_module 包时 尝试过的方法

问题描述

我正在尝试在我的 pickr 应用程序中使用 nuxt.js 包(一个颜色选择器库),在导入时它提供了名为 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.js 并使用 mode:client
  • 我制作了 pickr 包作为 nuxt 插件将它添加到 nuxt.config.js 并使用 ssr:false

但是没有用?

解决方法

经过挣扎,我想出了这种方法并且对我有用

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

,

您可以尝试将其包装在自定义 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');

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...