2017-04-20 59 views
0

试图从我的Graph.vue文件重复使用自定义模板,但此尝试失败(控制台中没有任何错误)。我只得到一张图表(红色)。任何想法如何解决这个代码?无法在Vue.js中重复使用模板

我当前的代码如下所示:

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> 

预期的结果应该是两个酒吧 - 红色和b一个。

回答

3

我认为你的安装点是错误的。 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> 
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 } 
    }); 
}