天天看點

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>


           

繼續閱讀