美文网首页Vue2vue学习
Vue+Echarts 实现自定义折线图组件

Vue+Echarts 实现自定义折线图组件

作者: JJIIMM | 来源:发表于2017-06-26 13:38 被阅读357次

    网上Vue结合Echarts使用的例子少之又少,而且数据都写好在组件内且不可复用

    本文基于Vue.js高仿饿了么外卖App,在商家页面添加一个简易的可交互的平滑折线图

    Chrome调试模拟手机端操作效果:


    </br>
    我将拆分为两个部分,标题和三个选择框写在当前页面seller.vue中,将配置折线图的样式都写在父组件seller.vue里,折线图则抽象化为可复用的组件。

    </br>

    模拟一份JSON格式的 折线图xy坐标轴数据 chartData ,其中分了日、周、月这三组数据。
    ** data.json:**

    "chartData": {
        "day": {
          "xData": ["06/11", "06/12", "06/13", "06/14", "06/15", "06/16", "06/17"],
          "yData": [34, 38, 30, 28, 45, 49, 37]
        },
        "week": {
          "xData": ["31周","32周","33周","34周","35周","36周","37周"],
          "yData": [210, 247, 279, 258, 186, 171, 230]
        },
        "month": {
          "xData": ["1月","2月","3月","4月","5月","6月","7月"],
          "yData": [876,802,878,861,759,871,832]
        }
      }
    

    </br>

    在 webpack 的 dev-sever.js 中读取模拟好的 chartData 数据,然后新增个接口apiRoutes,当服务端收到请求以后,返回给客户端 chartData
    ** dev-sever.js:**

    ......
    var chartData = appData.chartData
    ......
    apiRoutes.get('/chartData', function (req, res) {
     res.json({
       errno: 0,
       data: chartData
     });
    })
    ......
    

    </br>

    Hello.vue向服务器请求并获取 chartData
    Hello.vue:

    <template>
      ......
        <keep-alive>
          <router-view :seller="seller" :chartData="chartData"></router-view>
        </keep-alive>
      ......
    </template>
    
    <script>
        ......
        created() {
          ......
          this.$http.get('/api/chartData').then((response) => {
            response = response.body;
            if (response.errno === ERR_OK) {
              this.chartData = response.data;
              console.log(this.chartData);
            }
          });
        },
      ......
    </script>
    

    </br>

    seller.vue 中写好标题和三个选择框的样式

    props 接收从 Hello.vue 传来的xy坐标轴数据 chartData

    传入 chart.vue 将要接收的数据,impData 为 chartData 中的一组数据,setData 为自定义折线图样式的数据。

    select(type) 方法是点击选择框高亮,并把 impData 赋值为 chartData 中对应的一组数据

    ** seller.vue :**

    <template>
      <div class="seller" ref="seller">
        <div class="seller-content">
          ......
          <div class="lineChart">
            <div class="chartTitle">总销售量</div>
            <div class="time-type">
              <span @click="select('day')" class="block" :class="{'positive':positiveType==='day'}">日</span>
              <span @click="select('week')" class="block" :class="{'positive':positiveType==='week'}">周</span>
              <span @click="select('month')" class="block" :class="{'positive':positiveType==='month'}">月</span>
            </div>
            <chart class="chart" :impChartData="impData" :setChartData="setData"></chart>
          </div>
          ......
        </div>
      </div>
    </template>
    
    <script>
      import chart from '../../components/chart/chart';
    
      export default {
        props: {
          seller: {
            type: Object
          },
          chartData: {
            type: Object
          }
        },
        data() {
          return {
            positiveType: "day",
            impData: this.chartData.day,
            setData: {
              xAxisColor: '#B03A5B',
              lineColor: '#60C0DD',
              grid: {
                  y: 45,
                  x2: 40,
                  y2: 90,
                  x: 60
              }
            }
          };
        },
        ......
        methods: {
          select(type) {
            this.positiveType = type;
            this.impData = this.chartData[type];
          }
        },
        components: {
          chart
        }
      };
    </script>
    
    <style lang="stylus" rel="stylesheet/stylus">
    ......
        .lineChart
          .chartTitle
            border-left: 3px solid #B03A5B
            padding: 0 12px
            height: 28px
            line-height: 28px
            font-size: 14px
            color: #07111b
            background: #f3f5f7
          .time-type
            padding: 18px 18px 0  18px
            font-size: 0
            .block
              display: inline-block
              padding: 8px 12px
              margin-right: 8px
              line-height: 16px
              border-radius: 1px
              font-size: 12px
              color: rgb(77, 85, 93)
              background: rgba(243, 245, 247, 0.9)
              &.positive
                background: rgba(176, 58, 91, 0.2)
          .chart
            width: 100%
    .....
    </style>
    

    </br>

    chart.vue组件中

    prop 接收父组件 seller.vue 的传来的 impChartData 和 setChartData

    watch 观察 impChartData 数据的变化,因为父组件点击选择框会改变传入的数据,这里相应的改变数据,并渲染新的折线图

    drawLine(xData, yData, xAxisColor, lineColor, grid) 是绘制折线图样式的主体,我提取出了五个属性值作为参数,
    分别是x坐标轴数据、y坐标轴数据、x坐标轴指示器的颜色、折线线条的颜色、直角坐标系内绘图网格,
    分别获取自 this.impChartData.xData、 this.impChartData.yData、 this.setChartData.xAxisColor、 this.setChartData.lineColor、 this.setChartData.grid

    Echarts的配置项很多,如果想自定义更加个性化的样式,比如多条折线、两个x轴坐标,都可以设置为参数。

    GitHub 上已经有达人做了几张图的基本模板 v-charts ,很方便就是可配置项比较少。

    chart.vue:

    <template>
      <div v-show="impChartData" class="myChart" id="myChart"></div>
    </template>
    
    <script>
    // import echarts from 'echarts';
    let echarts = require('echarts/lib/echarts');
    require('echarts/lib/chart/line');
    require('echarts/lib/component/tooltip');
    require('echarts/lib/component/markPoint');
    
    export default {
      props: {
        impChartData: {
          type: Object
        },
        setChartData: {
          type: Object
        }
      },
      data() {
        return {
          myLineChart: null
        };
      },
      created() {
        this.$nextTick(() => {
          this.myLineChart = echarts.init(document.getElementById('myChart'));
          this.drawLine(this.impChartData.xData, this.impChartData.yData, this.setChartData.xAxisColor, this.setChartData.lineColor, this.setChartData.grid);
        });
      },
      watch: {
          'impChartData'() {
            this.$nextTick(() => {
              this.drawLine(this.impChartData.xData, this.impChartData.yData, this.setChartData.xAxisColor, this.setChartData.lineColor, this.setChartData.grid);
          });
        }
      },
      methods: {
        drawLine(xData, yData, xAxisColor, lineColor, grid) {
          this.myLineChart.setOption({
              tooltip: {
                  trigger: 'axis'
              },
              grid: grid,
              xAxis: [{
                  type: 'category',
                  data: xData,
                  axisPointer: {
                      lineStyle: {
                          color: xAxisColor,
                          opacity: 0.2,
                          width: 1
                      },
                      label: {
                          show: true,
                          backgroundColor: xAxisColor
                      },
                      handle: {
                          show: true,
                          color: xAxisColor
                      }
                  }
              }],
              yAxis: [{
                  type: 'value',
                  name: '份',
                  splitNumber: 4
              }],
              series: [{
                  name: '总销售量',
                  type: 'line',
                  smooth: true,
                  data: yData,
                  markPoint: {
                      data: [{
                          type: 'max',
                          name: '最大值'
                      }]
                  },
                  itemStyle: {
                      normal: {
                          color: lineColor
                      }
                  }
              }]
          });
          window.onresize = this.myLineChart.resize;
        }
      }
    };
    </script>
    
    <style lang="stylus" rel="stylesheet/stylus">
      .myChart
        width: 100%
        height: 280px
    </style>
    

    </br>
    参考文档:
    Echarts 配置项

    相关文章

      网友评论

        本文标题:Vue+Echarts 实现自定义折线图组件

        本文链接:https://www.haomeiwen.com/subject/yvkdcxtx.html