在您的示例中,该type
属性有效地决定了使用哪个组件。内置属性is
更适合这项工作。请注意,这里我仍然注册所有组件,但是使用 util 函数使代码非常简短和容易。
<div id="app">
<div>
<!-- think of :is like the :type property in your example, it serves the same purpose -- deciding which component to use -->
<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>
https://codepen.io/anon/pen/MBxRpP