我正在尝试使用 Choices.js在 Vue 组件中。组件编译成功,但随后触发错误:
[vue-router] Failed to resolve async component default: ReferenceError: document is not defined
在浏览器中我看到:
ReferenceError document is not defined
我觉得这和Nuxt.js中的SSR有关系?我只需要 Choices.js 在客户端上运行,因为我猜它只是一个客户端方面。
nuxt.config.js
build: {
vendor: ['choices.js']
}
AppCountrySelect.vue
<script>
import Choices from 'choices.js'
export default {
name: 'CountrySelect',
created () {
console.log(this.$refs, Choices)
const choices = new Choices(this.$refs.select)
console.log(choices)
}
}
</script>
在经典的 Vue 中,这会很好地工作,所以我仍然非常了解如何让 Nuxt.js 以这种方式工作。
我哪里出错了?
谢谢。
最佳答案
这是启动 Nuxt 项目时的常见错误 ;-)
Choices.js 库仅适用于客户端!所以 Nuxt 尝试从服务器端渲染,但是从 Node.js window.document
不存在,那么你有一个错误。
注意:window.document
只能从浏览器渲染器中获得。
自 Nuxt 1.0.0 RC7 , 你可以使用 <no-ssr>
元素以允许您的组件仅用于客户端。
<template>
<div>
<no-ssr placeholder="loading...">
<your-component>
</no-ssr>
</div>
</template>
看这里的官方例子:https://github.com/nuxt/nuxt.js/blob/dev/examples/no-ssr/pages/index.vue
更新:
自 Nuxt >= 2.9.0 , 你必须使用 <client-only>
元素而不是 <no-ssr>
:
<template>
<div>
<client-only placeholder="loading...">
<your-component>
</client-only>
</div>
</template>
要了解更多信息,请参阅 nuxt 文档:https://nuxtjs.org/docs/2.x/features/nuxt-components#the-client-only-component
关于javascript - Nuxt.js 中的 "document is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058544/