Reputation: 341
I want to make my code shorter. I have chart js which is using datacollection
to set options for the chart. I want to render it in another component at use it on my pages.
I want to be able to set det data collection from the component render, based on which chart I want.
I have something like this in my component:
<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>
So I want to be able to go down in my component and set the datacollection
. How can I do that?
Thanks in advance.
Upvotes: 0
Views: 372
Reputation: 821
I think you're looking for component props.
<template>
<div>
<chart :data-collection="myChartData"></chart>
</div>
</template>
<script>
export default {
name: "this-chart",
props: {
myChartData: {
type: Array,
required: true
}
}
};
</script>
And to use it
<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>
Please format your code better next time.
Upvotes: 1
Reputation: 821
Then based on your comment you could to something like this. Probably more elegant way but should work.
<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>
and then to use
<template>
<this-chart activeDataSet="a"></this-chart>
</template>
Upvotes: 1