组件中的Vue JS设置数据收集

时间:2018-08-31 08:02:55

标签: javascript vue.js chart.js vue-component

我想简化我的代码。我有一个图表js,它使用datacollection来设置图表的选项。我想在页面上使用它时将其呈现在另一个组件中。

我希望能够根据所需图表从组件渲染器设置det数据收集。

我的组件中有类似的内容

<template>
   <div>
     <chart :datacollection="this_will_i_define_on_the_page_i_render_this_component"> </chart>
   </div>
<template>

<script> 
  export {
    name: 'this-chart',
    data () { 
      return {
       DC1: []
       DC2: []
      }
    }
 }
 (basic vue component)
</script>


<template>
  <this-chart :datacollection="DC1"> </this-chart>
  <this-chart :datacollection="DC2"> </this-chart>
</template>

因此,我希望能够进入组件并设置datacollection。我怎样才能做到这一点?

谢谢。

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找component props

<template>
    <div>
        <chart :data-collection="myChartData"></chart>
    </div>
</template>

<script>
export default {
  name: "this-chart",
  props: {
    myChartData: {
      type: Array,
      required: true
    }
  }
};
</script>

并使用它

<template>
    <this-chart :my-chart-data="exampleData"></this-chart>
</template>

<script>
export default {
  name: "example-component",
  data() {
    return {
      exampleData: [{ x: 5, y: 10 }, { x: 6, y: 11 }]
    };
  }
};
</script>

请下次更好地格式化代码。

答案 1 :(得分:1)

然后根据您的评论,您可以进行如下操作。也许是更优雅的方式,但应该可以。

<template>
    <div>
        <chart :data-collection="myChartData"></chart>
    </div>
</template>

<script>
export default {
  name: "this-chart",
  props: {
    activeDataSet: {
      type: String,
      required: true,
      validator: value => ["a", "b", "c"].indexOf(value) > -1
    }
  },
  computed: {
    myChartData() {
      const example1 = [{ x: 1, y: 2 }, { x: 2, y: 3 },{ x: 3 y: 4 }];
      const example2 = [{ x: 1, y: 2 }, { x: 2, y: 3 },{ x: 3 y: 4 }];
      const example3 = [{ x: 1, y: 2 }, { x: 2, y: 3 },{ x: 3 y: 4 }];
      if(this.activeDataSet === 'a') return example1
      if(this.activeDataSet === 'b') return example2
      if(this.activeDataSet === 'c') return example3
    }
  }
};
</script>

然后使用

<template>
    <this-chart activeDataSet="a"></this-chart>
</template>
相关问题