vue中使用echarts的两种方法

发布时间 2023-04-11 11:09:39作者: 漫思

vue中使用echarts的两种方法

Posted on 2021-08-15 18:59  书中枫叶  阅读(33524)  评论(1)  编辑  收藏  举报

在vue中使用echarts有两种方法
一、第一种方法
1、通过npm获取echarts

npm install echarts --save

2、在vue项目中引入echarts

在 main.js 中添加下面两行代码

import * as echarts from ‘echarts’;

Vue.prototype.$echarts = echarts

注:import echarts from 'echarts' 引入echarts后,不能全局使用echarts,所以通过Vue.prototype将echarts保存为全局变量。原则上$echarts可以为任意变量名。

3、新建Echarts.vue文件

在 template 中添加一个存放echarts的‘div’容器
添加 myEcharts() 方法,将官方文档中的script内容复制到myEcharts()中
修改 echarts.init() 为 this.$echarts.init() ,因为上面第二部,将echarts保存到全局变量$echarts中。
在mounted中调用myEcharts()方法

复制代码
//在Echarts.vue文件中
<template>
  <div class="Echarts">
    <div id="main" style="width: 600px;height: 400px;"></div>
  </div>
</template>
 
<script>
export default {
  name: 'Echarts',
  methods: {
    myEcharts(){
      var myChart = this.$echarts.init(document.getElementById('main'));
      //配置图表
      var option = {
        title: {
          text: 'echarts入门示例',
        },
        tooltip: {},
        legend: {
          data: ['销量']
        },
        xAxis: {
          data: ['衬衫','羊毛衫','雪纺衫','裤子','高跟鞋','袜子']
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [5,20,36,10,10,20]
        }]
      };
      myChart.setOption(option);
    }
  },
  mounted(){
    this.myEcharts();
  }
}
</script>
 
<style>
 
</style>
复制代码

 

注:本例函数中使用ES6写法。mounted(){}等同于mounted:function(){}。myEcharts()方法同理。最后添加进行路由配置。

二、使用vue-echarts
1、先npm安装vue-echarts

npm install echarts vue-echarts

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

复制代码
//在main.js中引入
 
 
import Echarts from 'vue-echarts'
import 'echarts/lib/chart/line'
 
Vue.component('chart',Echarts)
复制代码

3、然后在组件中使用

复制代码
//hello.vue中
 
<template>
  <div class="hello">
    <chart ref="chart1" :options="orgOptions" :auto-resize="true"></chart>
  </div>
</template>
 
<script>
export default {
  name: 'hello',
  data() {
    return {
      orgOptions: {},
    }
  },
  mounted() {
    this.orgOptions = {
      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
      }]
    }
  }
}
</script>
 
<style>
 
</style>
复制代码

 

 

本文来自博客园,作者:书中枫叶,转载请注明原文链接:https://www.cnblogs.com/zy-mg/p/15144380.html