I'm trying to use the D3 extension in a Nuxt 3 project and for that I created a d3.client.js
file in the plugins/
directory.
import * as d3 from "d3";
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(d3)
})
However, when I try to use it gives me a 500 Internal Server Error document is not defined
.
<script>
import * as d3 from "d3";
export default {
name: "globe",
created() {
d3.select("#globe");
}
}
</script>
How can I solve this?
CodePudding user response:
d3.select()
uses document.querySelector()
under the hood. Since you're working server side, you don't have access to document
yet. So you'll need to mock it or to avoid using it.
You can avoid using it all together by passing an element instead of a string to d3.select()
, as it will then create a functioning d3 selection without running document.querySelector()
. And since every other chained .select()
or .selectAll()
uses previousSelection.querySelector()
, you can just continue from there.
If you do not have access to the DOM element directly, you might want to mock document
. This article suggests using 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');
CodePudding user response:
I managed to solve it by using the d3.select
with a Vue reference.
const globe = d3.select(this.$refs.globe)