在Vue中使用echarts的两种方式

方式一、直接引入echarts


先npm安装echarts

npm install echarts --save

 

代码:

main.js

import myCharts from './comm/js/myCharts.js'
Vue.use(myCharts)

myCharts.js

/**
 * 各种画echarts图表的方法都封装在这里
 * 注意:这里echarts没有采用按需引入的方式,只是为了方便学习
 */

import echarts from 'echarts'
const install = function(Vue) {
    Object.defineProperties(Vue.prototype, {
        $chart: {
            get() {
                return {
                    //画一条简单的线
                    line1: function (id) {
                        this.chart = echarts.init(document.getElementById(id));
                        this.chart.clear();

                        const optionData = {
                            xAxis: {
                                type: 'category',
                                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [{
                                data: [820, 932, 901, 934, 1290, 1330, 1320],
                                type: 'line',
                                smooth: true
                            }]
                        };

                        this.chart.setOption(optionData);
                    },
                }
            }
        }
    })
}

export default {
    install
}

HelloWorld.vue






效果

在Vue中使用echarts的两种方式_第1张图片

方式二、使用vue-echarts


先npm安装vue-echarts

npm install echarts vue-echarts

 

代码:

除了全量引用echarts,我们还可以采用按需引入的方式
main.js

import ECharts from 'vue-echarts'
import 'echarts/lib/chart/line'
Vue.component('chart', ECharts)

 Helloworld.vue




 博主建议:如果只是小需求,不要求太高,可以使用vue-echarts;但是如果要求高,需求大,那么建议用echarts,因为echarts的官方文档写的很详细,vue-echarts的文档相对较少,虽然两者用法几乎一样,但是在部分功能实现还是有差别的。

你可能感兴趣的:(web前端,echart,echarts,vue.js,javascript)