javascript - Nuxt.js 中的 "document is not defined"

标签 javascript vue.js vuejs2 nuxt.js

我正在尝试使用 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/

相关文章:

javascript - 添加事件监听器以在 videojs 中的运行时获取视频持续时间

javascript - 你如何对 JavaScript 代码进行性能测试?

javascript - 如何在 Nativescript 应用程序中调用 axios/api 调用

javascript - 如何获取下一个文本输入的值?

javascript - MS 团队上的 Botframework : copy paste input not parsed to the backened

javascript - 无法使用 Pinia Store 从状态检索数据

javascript - Vue v-on :click does not work on component

typescript - Vue 实例未获取 shims-vue.d.ts 文件

javascript - 我应该如何在 Vue 的模式中动态添加和删除数据?

vue.js - Vue.js 中的条件 <router-link> 依赖于 prop 值?