我想在一个 .vue 组件
和一个 .js
文件中从 chart.js 创建多个图表,我该如何创建它?
到目前为止,我尝试为每个图表创建另一个 .js
文件。
这里是我的代码
LineChart.js 文件
import {Line} from 'vue-chartjs'
export default {
extends: Line,
mounted () {
this.renderChart({
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'Data One',
backgroundColor: '#FC2525',
data: [40, 39, 10, 40, 39, 80, 40]
},{
label: 'Data Two',
backgroundColor: '#05CBE1',
data: [60, 55, 32, 10, 2, 12, 53]
}
]
}, {responsive: true, maintainAspectRatio: false})
}
}
Step2.vue组件
<template>
<div class="Chart">
<h2>Linechart</h2>
<line-example></line-example>
</div>
</template>
<script>
import LineExample from './LineChart.js'
export default {
name: 'tes',
components: {
LineExample
}
}
</script>
此代码适用于一个图表,如果我想添加更多图表,则必须创建另一个 .js
文件。
最佳答案
你可以使用props
。
注意 - 对于 react 性问题,您可以查看 https://vue-chartjs.org/guide/#updating-charts
JS
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
props: {
labels: Array,
datasets: Object
},
mounted () {
this.renderChart({
labels: this.labels,
datasets: this.datasets,
}, {responsive: true, maintainAspectRatio: false})
}
}
组件
<template>
<div class="Chart">
<h2>Linechart 1</h2>
<line-example :labels="labels" :datasets="datasets"></line-example>
<h2>Linechart 2</h2>
<line-example :labels="labels2" :datasets="datasets2"></line-example>
</div>
</template>
<script>
import LineExample from './LineChart.js'
export default {
name: 'tes',
components: {
LineExample
},
data () {
return {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
labels2: ['Foo', 'Bar'],
datasets: [
{
label: 'Data One',
backgroundColor: '#FC2525',
data: [40, 39, 10, 40, 39, 80, 40]
},{
label: 'Data Two',
backgroundColor: '#05CBE1',
data: [60, 55, 32, 10, 2, 12, 53]
}
],
datasets2: [
{
label: 'Data One',
backgroundColor: '#FC2525',
data: [1, 2]
},{
label: 'Data Two',
backgroundColor: '#05CBE1',
data: [3, 4]
}
]
}
}
}
</script>
关于javascript - 如何在一个组件vue上创建多个图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56625259/