1. 程式人生 > 實用技巧 >vue 使用echarts 一個小案例 寬度自適應

vue 使用echarts 一個小案例 寬度自適應

以元件的形式引入專案中

元件:

<template>
    <div>
        <div :class="className" :id="id" :style="{height:height,width:width}"></div>
    </div>
</template>

<script>
// 引入基本模板
let echarts = require("echarts/lib/echarts");
// 引入柱狀圖元件
require("echarts/lib/chart/bar");
// 引入提示框和title元件
require("echarts/lib/component/tooltip");
//分類標題
require("echarts/lib/component/legend");

export default {
    props:['sourse'],
    data() {
        return {
            className: "echarts",
            id: "main",
            height: "360px",
            width: "100%",
            option: {
                legend: {},
                color: ["#3C90F7", "#E05667", "#1AB394", "#F4CD49"],
                dataset: {
                    source:this.sourse,
                },
                xAxis: {
                    type: "category",
                    axisTick: {
                        show: false,
                    },
                },
                tooltip:{
                    show:true
                },
                yAxis: {},
                series: [
                    {
                        type: "bar",
                        seriesLayoutBy: "row",
                    },
                    {
                        type: "bar",
                        seriesLayoutBy: "row",
                    },
                    {
                        type: "bar",
                        seriesLayoutBy: "row",
                    },
                    {
                        type: "bar",
                        seriesLayoutBy: "row",
                    },
                ],
            },
        };
    },
    mounted() {
        var myChart = echarts.init(document.getElementById("main"));
        // console.log(myChart);
        this.$nextTick(_=>{
            myChart.setOption(this.option);
        })
        window.addEventListener('resize',this.resize())
    },
    methods:{
//自適應寬度 resize(){ let that = this; let timer = null; return function(){ if(timer){ clearTimeout(timer) } timer=setTimeout(()=>{ var myChart = echarts.init(document.getElementById("main")); myChart.resize(); }) } } } }; </script> <style lang='scss' scoped> </style>

  父元件:

引用:

<bar :sourse='sourse'></bar>

  資料:

 sourse: [["type", "行政部", "財務部","技術部","車間"],
                        ["期初人數", 320, 332, 301, 334],
                        ["新入職人數", 220, 182, 191, 234],
                        ["離職人數", 150, 232, 201, 154],
                        ["期末人數", 98, 77, 101, 99]
            ],

  注: 上文echarts 自適應寬度,轉載自https://blog.csdn.net/gobacka/article/details/89183993