【问题标题】:Client-only Nuxt 3 D3 plugin仅限客户端的 Nuxt 3 D3 插件
【发布时间】:2022-01-15 20:27:26
【问题描述】:

我正在尝试在 Nuxt 3 项目中使用 D3 扩展,为此我在 plugins/ 目录中创建了一个 d3.client.js 文件。

import * as d3 from "d3";
import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.vueApp.use(d3)
})

但是,当我尝试使用它时,它会给我一个 500 Internal Server Error document is not defined

<script>
import * as d3 from "d3";

export default {
    name: "globe",
    created() {
        d3.select("#globe");
    }
}
</script>

我该如何解决这个问题?

【问题讨论】:

    标签: d3.js nuxt3


    【解决方案1】:

    d3.select() 在后台使用document.querySelector()。由于您在服务器端工作,因此您还无权访问document。所以你需要模拟它或避免使用它。

    您可以通过将元素而不是字符串传递给d3.select() 来避免一起使用它,因为它会在不运行document.querySelector() 的情况下创建有效的d3 选择。由于所有其他链接的.select().selectAll() 都使用previousSelection.querySelector(),因此您可以从那里继续。

    如果您无法直接访问 DOM 元素,您可能需要模拟 documentThis article 建议使用JSDOM

    import { JSDOM } from 'jsdom';
    
    // create a new JSDOM instance for d3-selection to use
    const document = new JSDOM().window.document;
    
    d3.select(document.body)
      .append('div');
    

    【讨论】:

    • 这也不好用
    【解决方案2】:

    我设法通过使用带有 Vue 参考的 d3.select 来解决它。

    const globe = d3.select(this.$refs.globe)
    

    【讨论】:

      猜你喜欢
      • 2022-09-25
      • 1970-01-01
      • 2022-08-20
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2015-09-28
      • 2021-12-21
      相关资源
      最近更新 更多