Home > database >  Vue - script-setup data to script for charts
Vue - script-setup data to script for charts

Time:01-19

First let me clarify, i'm new to vue.

What I am trying to do is, when I get data from the defineProps. I want that the data from the defineProps goes to my script. Only I cant get the data over there. It is only available in the <template> {{ graph }} </template>. Notice that i can access the data with {{ graph }} in there. I just cant find a way to use it in export default { }

So my script is looking like this

<script setup>
const props = defineProps(['graph']);
</script>

<template>
 {{ graph }} // Works
</template>

<script>
console.log(props); // Doesnt work or
console.log(graph); // Doesnt work
export default {
}
</script>

So, how do I get the data from props(graph) into export default { }?

Why do I want do this?

I saw https://vue-chartjs.org/examples/ and I followed it.

export default {
  name: 'BarChart',
  components: { Bar },
  data() {
    return {
      chartData: {
        labels: [ 'January', 'February', 'March' ],
        datasets: [ { data: [3, 20, 12] } ]
      },
      chartOptions: {
        responsive: true
      }
    }
  }
}

Notice the data: [3, 20, 12]. I want to edit the values with the data I get. For example data: [props.day1, props.day2, props.day3]

CodePudding user response:

Like commented, use just script setup, try like following:

<template>
  <Bar :data="chartData" :options="chartOptions" />
</template>
<script setup>
  import { Bar } from 'vue-chartjs'
  import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'
  import { ref } from 'vue'
  ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

  const chartData = ref({
    labels: [ 'January', 'February', 'March'],
    datasets: [
      {
        label: 'Data One',
        backgroundColor: '#f87979',
        data: [40, 20, 12]
      }
    ]
  })
  const chartOptions = ref({
    responsive: true,
    maintainAspectRatio: false
  })
</script>

demo HERE

  • Related