[Vuejs]-How to assign value to another javascript library with Vue?

0👍

As a follow up to my comment, I am posting components from a sample Chart.js project that I built recently. It demonstrates the idea that I was describing in my comment. It was written in Vue.js 2 using the Vue CLI.

chart-configurations.js

const samplePieConfig = {
  type: 'pie',
  data: {
    datasets: [{
      data: [],
      backgroundColor: [
        'rgba(255, 0, 0, 0.8)',
        'rgba(0, 255, 0, 0.8)',
        'rgba(0, 0, 255, 0.8)',
      ]
    }],
    // These labels appear in the legend and in the tooltips when hovering different arcs
    labels: [
      'Red',
      'Green',
      'Blue'
    ]
  },
  options: {
    responsive: false
  }
}

export {
  samplePieConfig
}

ChartTest.vue

<template>
  <div class="chart-test">
    <h3>Chart Test</h3>
    <canvas id="chart-canvas" width="500" height="500" ref="chartref"></canvas>
  </div>
</template>

<script>
  import Chart from 'chart.js';
  import { samplePieConfig } from '@/chart-configurations.js'

  export default {
    data() {
      return {
        chartObj: null,
        chartConfig: samplePieConfig
      }
    },
    props: {
      chartData: {
        type: Array,
        required: true
      }
    },
    methods: {
      setChartData() {
        this.chartConfig.data.datasets[0].data = this.chartData;
      }
    },
    mounted() {
      this.setChartData();
      this.chartObj = new Chart(this.$refs.chartref, this.chartConfig);
    },
    // beforeDestroy() {
    //   // This necessary if canvas is reused for a new chart
    //   this.chartObj.destroy();
    // }
  }
</script>

App.vue

<template>
  <div id="app">
    <chart-test v-if="dataReady" :chartData="pieChartData" />
  </div>
</template>

<script>
  import ChartTest from '@/components/ChartTest'

  export default {
    name: 'App',
    components: {
      ChartTest
    },
    data() {
      return {
        barChartData: [12, 19, 3, 5, 2, 3],
        pieChartData: [10, 20, 30],
        dataReady: true
      }
    },
    methods: {
      getData() {
        this.dataReady = true;
      }
    },
    mounted() {
      // Simulate API call
      setTimeout(this.getData(), 2000);
    }
  }
</script>

0👍

since you have an asynchronous request, so you can not access dataTable until it fetched
change your ajax request like this:

$.ajax({
    type: "POST",
    url: that.url,
    data:{
        startDate:$('#startDate').val(),
        endDate:$('#endDate').val(),
        pageNumber:$('#pageNumber').val()
    },
    success: function (data) {
        console.log('data remote call');
        console.log(data.sqlData);
        that.dataTable = data.sqlData;
        that.$emit('data-fetched'); // fire an event when data was ready to use
    }
});

and outside your Vue instance you can listen that event like this:

app.$on('data-fetched', function(){
  console.log(app.$data.dataTable)
});

and it’s should work

Leave a comment