vue引入d3

 单页面使用

cnpm install d3 --save-dev

<script>
  import * as d3 from 'd3'

export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    testD3(){
      let test1 = d3.select("#test1").text();
      alert(test1)
    }
  }
}
</script>

<el-button type="primary" @click="testD3()">主要按钮</el-button>

使用yarn install d3安装后,idea提示找不到d3.select方法,但实际上方法可以运行生效,改为cnpm install d3 --save-dev重新安装了一次,不再有此提示了

全局使用

上面的方式需要在使用的vue视图中引入d3,页面多就得多次引用,可以使用全局的方式,将d3注册到Vue原型中

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)  // 引入Element

import * as d3 from 'd3'
Vue.prototype.$d3 = d3


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

重点是下面两行

import * as d3 from 'd3'
Vue.prototype.$d3 = d3

vue视图中使用,以$开头表示这是一个第三方插件变量,以区别于内部本身的变量,类似于jQuery的$

<script>

export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    testD3(){
      let a = this.$d3.select("#infoBtn").text();
      alert(a);
    }
  }
}
</script>

注意事项

d3中展示图形时,有自己的样式;

vue中可以使用scss,这两者可能会有冲突

解决方案:使用d3的视图中尽量避免使用scss

原文地址:https://www.cnblogs.com/perfei/p/13818870.html