【问题标题】:[Vue warn]: Error in beforeCreate hook: "ReferenceError: document is not defined"[Vue 警告]:beforeCreate 挂钩中的错误:“ReferenceError:文档未定义”
【发布时间】:2020-10-03 21:12:17
【问题描述】:

这可能是一个长镜头,但我无法弄清楚出了什么问题。希望有人能给我一些指导。

我在 Nuxt 项目中使用 vue 快速编辑插件:https://github.com/A1rPun/vue-quick-edit。

有时我会弹出错误:

[Vue 警告]:beforeCreate 钩子中的错误:“ReferenceError: document is 未定义”

这似乎只在我第一次加载页面时发生(未经证实!),之后它再也不会发生(使用 ctrl+F5,以隐身方式加载,在另一个浏览器中尝试,...),它只是从来没有再次显示,图书馆完美运行。

但是,这让我对使用该库犹豫不决,因为我不确定错误来自哪里以及它是否会影响我的最终用户。

这是我为使用内联可编辑字段而创建的组件:

<template>
  <quick-edit
    :aria-label="label"
    @input="updateValue"
  />
</template>

<script>
import QuickEdit from 'vue-quick-edit'

export default {
  components: { QuickEdit },
  props: {
    label: {
      type: String,
      required: true,
    },
  },
  methods: {
    updateValue (event) {
      // do something
    },
  },
}
</script>

<style lang="scss" scoped>

</style>

【问题讨论】:

    标签: javascript vue.js nuxt.js document


    【解决方案1】:

    当 Nuxt 在服务器端渲染页面时,组件尝试访问 DOM,解决方案是将其包裹在 client-only 中

    <template>
      <client-only>
         <quick-edit
           :aria-label="label"
           @input="updateValue"
         />
      </client-only>
    </template>
    

    【讨论】:

      【解决方案2】:

      这是因为Nuxt第一次在服务端渲染页面,所以document真的没有在服务端定义。

      您可以在 nuxt.config.js 中定义您的插件并告诉 nuxt 仅在客户端中使用它:

      在nuxt.config.js:

      ...
      plugins: [
          { src: "~/plugins/quickEdit.js", ssr: false }
      ]
      ...
      

      在~/plugins/quickEdit.js:

      import Vue from "vue";
      import QuickEdit from 'vue-quick-edit'
      
      Vue.use(QuickEdit);
      
      

      然后在你的组件中使用它。

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 2020-07-03
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        相关资源
        最近更新 更多