问题描述
我正在尝试在我的 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');