Extend VueJs Component based on properties - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Extend VueJs Component based on properties

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <style>
#app {// www . j a v  a 2 s .c  om
   width: 600px;
}
      </style> 
   </head> 
   <body translate="no"> 
      <div id="app"> 
         <div> 
            <component :is="chartTypeLine" :data="chartData" :options="chartOptions"></component> 
            <component :is="chartTypeBar" :data="chartData" :options="chartOptions"></component> 
         </div> 
      </div> 
      <script src="https://vuejs.org/js/vue.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script> 
      <script src="https://unpkg.com/vue-chartjs/dist/vue-chartjs.min.js"></script> 
      <script>
    const getChart = (type) => {
        switch (type) {
            case 'line-chart':
                return VueChartJs.Line;
            case 'bar-chart':
                return VueChartJs.Bar;
            default:
                throw new Error("wrong chart type");
        }
    };
    const chartTypes = ['line-chart', 'bar-chart'];
    //this makes registering all those components easier.
    chartTypes.forEach(type => {
        Vue.component(type, {
            extends: getChart(type),
            props: ['data', 'options'],
            mounted () {
                this.renderChart(this.data, this.options)
            }
        })
    });
    new Vue({
        el: '#app',
        data: {
            chartData: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [
                    {
                        backgroundColor: '#f87979',
                        data: [40, 39, 10, 40, 39, 80, 40]
                    }
                ]
            },
            chartOptions: {responsive: true, maintainAspectRatio: false},
            chartTypeLine: 'line-chart',
            chartTypeBar: 'bar-chart'
        }
    })
      </script>  
   </body>
</html>

Related Tutorials