天天看点

vue使用echarts制作折线图

效果图:

vue使用echarts制作折线图

在main.js中加载echarts和element-ui组件

import Vue from 'vue'
import App from './App.vue'

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

// 引入echarts
import echarts from 'echarts'
Vue.prototype.$echarts = echarts

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

           

创建一个echarts的组件

<template>
  <div id="main"></div>
</template>

<script>
export default {
  name: "EchartPractice",
  data () {
    return {

    }
  },
  methods: {
    drawChart (data) {
      let myEchart = this.$echarts.init(document.getElementById("main"));
      let option = {
        title: {
          text: '折线图'
        },
        tooltip: {
          trigger: 'item', //触发类型;轴触发,axis则鼠标hover到一条柱状图显示全部数据,item则鼠标hover到折线点显示相应数据,
          formatter: function (params) {
            return '当前温度为:' + params.data
          },
        },
        xAxis: {
          type: 'category',
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed"
            }
          }
        },
        series: [{
          data: data,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: 'blue'
          }
        }]
      };
      myEchart.setOption(option);
    },
  },

}
</script>

<style scoped>
#main {
  width: 600px;
  height: 400px;
  margin: auto;
  margin-top: 100px;
}
</style>
           

在app.vue中引入echarts组件

<template>
  <div class="EchartPractice">
    <div>
      <el-row>
        <el-col :span="12">
          <el-button @click="drawChart(data1)">data1</el-button>
          <el-button @click="drawChart(data2)">data2</el-button>
          <el-button @click="drawChart(data3)">data3</el-button>
          <el-button @click="drawChart(data4)">data4</el-button>
        </el-col>
        <el-col :span="12">
          <el-date-picker v-model="days"
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
        </el-col>
      </el-row>
    </div>
    <echarts ref="tb"></echarts>
  </div>
</template>

<script>
import echarts from './views/echarts'
export default {
  name: "EchartPractice",
  components: {
    echarts
  },
  data () {
    return {
      days: ['2020-01-01', '2021-03-03'],
      data1: [20, 30, 32, 11, 22, 20, 15, 25, 35, 14],
      data2: [40, 10, 15, 21, 30, 20, 12, 15, 15, 31],
      data3: [30, 35, 21, 12, 20, 25, 14, 35, 23, 13],
      data4: [20, 23, 15, 31, 30, 30, 35, 22, 19, 24],
    }
  },
  methods: {
    drawChart (index) {
      this.$refs.tb.drawChart(index)
    },
  },
  mounted () {
    // 因为要实现点击不能的数据渲染不同的列表,所以需要通过调用组件的ref去找组件里面的渲染方法,然后让网页去重新去渲染数据
    this.$refs.tb.drawChart(this.data1)
  }
}
</script>


           

继续阅读