当前位置:首页 > 前端 > Vue.js

在vue 脚手架项目中如何安装使用echarts

Vue是现在比较火的框架,Echarts也是比较好用的图表组件,下面分享下在vue项目中如何安装和使用Echarts:


安装echarts依赖

npm install echarts -save


全局引入

import echarts from 'echarts'
Vue.prototype.$echarts = echarts 


Demo如下:


调用Echarts:

export default {
  name: 'Hello vue and echarts',
  data () {
    return {
      msg: 'one test'
    }
  },
  mounted(){
    this.test();
  },
  methods: {
    test(){
        let myChart = this.$echarts.init(document.getElementById('myChart'))
        myChart.setOption({
            title: { text: '来自echarts的第一个图表Demo' },
            tooltip: {},
            xAxis: {
                data: ["帽子","袜子","手表","轮胎","红枣","打包袋"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        });
    }
  }
}

注意: 这里echarts初始化应在钩子函数mounted()中,这个钩子函数是在el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用


按需引入

全局引入会将所有的echarts图表打包,导致build.js文件过大,所以建议还是按需引入比较好。

// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱状图
require('echarts/lib/chart/bar')
// 引入提示框和title
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')

export default {
  name: 'Hello vue and echarts',
  data () {
    return {
      msg: 'one test'
    }
  },
  mounted(){
    this.test();
  },
  methods: {
    test(){
        let myChart = this.$echarts.init(document.getElementById('myChart'))
        myChart.setOption({
            title: { text: '来自echarts的第一个图表Demo' },
            tooltip: {},
            xAxis: {
                data: ["帽子","袜子","手表","轮胎","红枣","打包袋"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        });
    }
  }
}



读后有收获可以支付宝请作者喝咖啡
< 上一篇
文章评论
评论功能改造中...
湘ICP备15005320号-1 似懂非懂 Powered by doyo. 网站地图
返回顶部