2017-09-05 100 views
2

我想在Vue組件中使用Choices.js。該組件編譯成功,但隨後就會觸發一個錯誤:「文檔未定義」在Nuxt.js

[vue-router] Failed to resolve async component default: ReferenceError: document is not defined

在瀏覽器中我看到:

ReferenceError document is not defined

我覺得這事做與SSR在Nuxt.js?我只需要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以這種方式工作。

任何想法,我要去哪裏錯了?

謝謝。

回答

3

這是一個常見的錯誤,當你啓動一個項目Nuxt ;-)

Choices.js LIB僅適用於客戶端!所以Nuxt試圖從服務器端渲染器,但從Node.js window.document不存在,那麼你有一個錯誤。
nb: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

+0

感謝這個!任何想法我怎麼能然後用SSR輸出元素本身?如同一樣,一些JS需要在客戶端執行一個選擇列表,但我仍然想要在服務器上呈現實際的選擇列表。 –