JanLi
JanLi

Reputation: 71

d3js in vue as external script [ d3 is not defined ]

I tried to add script d3js in vue

but there's a problem said that d3 is not defined eror is like this

ReferenceError: d3 is not defined at VueComponent.drawRect (AddMatchingComp.vue?./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0:264) at VueComponent.mounted (AddMatchingComp.vue?./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0:283) at invokeWithErrorHandling (vue.esm.js:1862) at callHook (vue.esm.js:4216) at Object.insert (vue.esm.js:3145) at invokeInsertHook (vue.esm.js:6341) at Vue.patch [as patch] (vue.esm.js:6560) at Vue._update (vue.esm.js:3945) at Vue.updateComponent (vue.esm.js:4063) at Watcher.get (vue.esm.js:4476)

is there anything wrong with my code , why d3 is not defined even i have add the script in mounted

here is my code :

<template>
<div>
    <div id="svgHere">

    </div>
</div>
</template>

<script>
    name:"testD3",
    props:{
      
    },
    components: {
        
    },
    data(){
        return{
          
    },
    methods:{  
       
    },
    mounted(){
        let d3Script = document.createElement('script')
        d3Script.setAttribute('type', "text/javascript");
        d3Script.setAttribute('src', 'https://d3js.org/d3.v6.min.js')
        document.head.appendChild(d3Script) 

        var dataArray = [2,13,15,20]
        var svg = d3.select("#svgHere").append("svg").attr("width", '100%').attr("height", '100%');
        svg.selectAll('rect').data(dataArray).enter().append('rect')
            .attr('height', function(d,i){return d*10})
            .attr('width','70')
            .attr('fill','darkred')
            .attr('x',function(d,i){return 80*i}) 
            .attr('y',function(d,i){return 350*(d*10)});
    },
    created(){
     
    },
  }
</script>

Upvotes: 1

Views: 285

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should import it as follows :

<script>
import * as d3 from "d3";
export default{
 name:"testD3",
    props:{
      
    },
 ...

Upvotes: 2

Related Questions