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

JavaScript Vue.js

老丝Tony

2020-03-23

我正在尝试在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以这种方式工作。

有什么想法我要去哪里吗?

谢谢。

第2864篇《Nuxt.js中的“文档未定义”》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
2020.03.23

我发现现在no-ssr被替换为,我正在使用echart并遇到相同的问题,但是现在它可以正常工作了!

    <client-only>
        <chart-component></chart-component>
    </client-only>
阿飞卡卡西 2020.03.23

启动Nuxt项目时,这是常见错误;-)

Choices.js LIB仅适用于客户端!因此Nuxt尝试从服务器端进行渲染,但是从Node.js window.document不存在,那么您会遇到错误。
nb:window.document仅在浏览器渲染器中可用。

Nuxt 1.0.0 RC7开始,您可以使用<no-ssr>element将组件仅允许在客户端使用。

<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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android