尝试重用我的Graph.vue文件中的自定义模板,但此尝试失败(控制台中没有任何错误)。我只得到一张图表(红色图表)。有任何想法如何修复此代码?
我目前的代码如下:
main.js
import Vue from 'vue';
import Graph from './components/Graph.vue';
new Vue({
el: 'graph',
components: { Graph }
});
Graph.vue
<template>
<canvas height="400" width="600"></canvas>
</template>
<script>
import Chart from 'chart.js';
export default {
props: ['labels', 'values', 'color'],
props: {
labels: {},
values: {},
color: {
default: 'rgba(220,220,220,0.2)'
}
},
mounted(){
var data = {
labels: this.labels,
datasets: [
{
label: "My First dataset",
fill: true,
lineTension: 0.1,
backgroundColor: this.color,
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: this.values,
spanGaps: false
},
]
};
new Chart(this.$el, {type: 'line', data: data});
}
}
</script>
example.html的
<div style="width:600px" class="container">
<graph :labels="['January', 'February', 'March']"
:values="[10, 42, 4]"
color="red"
></graph>
</div>
<div style="width:600px" class="container">
<graph :labels="['May', 'June', 'July']"
:values="[100, 420, 99]"
color="blue"
></graph>
</div>
<script src="{{asset('/js/main.js')}}"></script>
预期结果应该是两个条形 - 红色和蓝色条形。
答案 0 :(得分:4)
我认为你的挂载点是错误的。在这种情况下,el: 'graph'
行为可能无法预测(它会以第一个图元素为目标吗?)。
使用类似的东西:
<强> JS:强>
new Vue({
el: '#graphContainer',
components: { Graph }
});
<强> HTML:强>
<div id="graphContainer">
<div style="width:600px" class="container>
<graph :labels="['January', 'February', 'March']"
:values="[10, 42, 4]"
color="red"></graph>
</div>
<div style="width:600px" class="container">
<graph :labels="['May', 'June', 'July']"
:values="[100, 420, 99]"
color="blue"></graph>
</div>
</div>
答案 1 :(得分:0)
我更喜欢@Cobaltway回答,但这也解决了这个问题 的 JS:强>
import Vue from 'vue';
import Graph from './components/Graph.vue';
const graphs = document.querySelectorAll('graph');
for (let i = 0; i < graphs.length; ++i) {
new Vue({
el: graphs[i],
components: { Graph }
});
}