Loading D3 with Nuxt/Vue

佐手、 提交于 2019-12-10 14:22:12

问题


I am trying to implement D3 in an app I am building with Nuxt. I have successfully imported it into a view in the <script> section with import * as d3 from 'd3' however because the app is being rendered server-side D3's functionality doesn't work (i.e. d3.select(...)) due to the lack of browser. In the Nuxt plugin documentation it suggests a pattern for client-only external plugins:

module.exports = {
  plugins: [
    { src: '~plugins/vue-notifications', ssr: false }
  ]
}

I attempted to implement the pattern in the nuxt.config.js of my project:

module.exports = {
  head: {
    title: 'My Demo App',
    meta: [...],
    link: [...]
  },

  loading: {...},

  plugins: [
     { src: '~node_modules/d3/build/d3.js', ssr: false}
  ]
}

However D3 throws a ReferenceError while looking for document and Nuxt throws a SyntaxError in the console pointing to something in the plugins field of nuxt.config.js.

For reference, demo.vue:

<template>
  <div class="demo-container"></div>
</template>

<script>
  import * as d3 from 'd3';
  d3.select('.demo-container');
</script>

Would someone be able to point to what I'm doing wrong?


回答1:


For anyone coming to this page looking for a solution, these suggestions from piyushchauhan2011 here on GitHub sent me to the right direction —

All I needed to do was import d3 in my single file component and then do any dom manipulation with d3 only within mounted() like here

Before all this, I had to of course add d3 to my project with yarn add d3 (or npm install d3 --save).



来源:https://stackoverflow.com/questions/44121264/loading-d3-with-nuxt-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!