Nuxt.js 中的“文档未定义”

新手上路,请多包涵

我正在尝试在 Vue 组件中使用 Choices.js 。组件编译成功,但随后触发错误:

[vue-router] 无法解析异步组件默认值:ReferenceError:文档未定义

在浏览器中我看到:

ReferenceError 文档未定义

我认为这与 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 以这种方式工作。

我哪里出错了有什么想法吗?

谢谢。

原文由 Michael Giovanni Pumo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 466
2 个回答

当您启动 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

原文由 Nicolas Pennec 发布,翻译遵循 CC BY-SA 4.0 许可协议

接受的答案(虽然正确)太短了,我无法理解和正确使用它,所以我写了一个更详细的版本。我一直在寻找一种使用plotly.js + nuxt.js的方法,但它应该与OP的Choice.js + nuxt.js问题相同。

我的组件.vue

 <template>
  <div>
    <client-only>
      <my-chart></my-chart>
    </client-only>
  </div>
</template>
<script>
export default {
  components: {
    // this different (webpack) import did the trick together with <no-ssr>:
    'my-chart': () => import('@/components/MyChart.vue')
  }
}
</script>

MyChart.vue

 <template>
  <div>
  </div>
</template>
<script>
import Plotly from 'plotly.js/dist/plotly'
export default {
  mounted () {
    // exists only on client:
    console.log(Plotly)
  },
  components: {
    Plotly
  }
}
</script>

更新:在 Nuxt v>2.9.0 中有 <client-only> 标签而不是 < <no-ssr> ,请参阅@Kaz 的评论。

原文由 Michal Skop 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题