Quantum
Quantum

Reputation: 288

How can I display desired/particular chart in App.vue from Charts.vue which contains different charts in Vuejs

I am using Chartjs in order to display charts, I have created charts.vue component in which different charts are defined.

Here is my Charts.vue:

<template>
  <div class="chart-containr">
    <canvas ref="chart1"></canvas>
    <canvas ref="chart2"></canvas>
  </div>
</template>

<script>
...
</script>

Here is my App.vue:

<template>
  <div class="content-1">
    <charts/>  <-- Here i want to display my chart 1
  </div>

  ....

  <div class="content-8">
    <charts/>  <-- Here i want to display my chart 2
  </div>
</template>

<script>
import chart from './Charts'
exprt default{
  name: 'App',
  component: {chart}

    ....

}

As you can see in my App.vue, i have imported the Charts.vue and i have used charts as a component, but if i use it in the template part as both the charts are display one after another. Rather i want chart1 in the 1st div and chart2 in the 8th div.

Please help me in this, i want to display particular chart from the charts.vue in different part of App.vue. I tried using props but dint work out.

Upvotes: 0

Views: 145

Answers (1)

kissu
kissu

Reputation: 46602

You could probably use a prop and interpolate the id on the component.

Charts.vue (should be renamed to Chart.vue in this way I guess)

<template>
  <div class="chart-containr">
    <canvas :ref="`chart${chartId}`"></canvas>
  </div>
</template>

<script>
export default {
  props: {
    chartId: {
      type: String,
      default: '',
    },
  },
}
</script>

App.vue

<template>
  <div class="content-1">
    <charts chart-id="1"></charts>
  </div>

  <div class="content-8">
    <charts chart-id="2"></charts>
  </div>
</template>

There is maybe also a way with slots but props will be enough here.
Btw, you could even v-for and display the <charts> component programmaticaly.

Upvotes: 4

Related Questions