[Chartjs]-Vue.js access variable from method

1πŸ‘

Yes, you can access variables in data() from mounted().

You need to prepend variables with this. when using the Options API

ex: this.prices[0].price

1πŸ‘

As you are putting watcher on selected but I did not see any changes in the selected variable in your code. As per my understanding you are making an API call to get the graph data based on the selected option.

If Yes, Instead of generating a chart in mounted you can generate it inside your getPrice() method itself based on the response. It should be :

methods: {
  getPrice: function () {
    var this_ = this;
    axios
      .get(
      "https://site/...."
    )
      .then((response) => {
      this.generateChart(response.data);
    })
  },
    generateChart(prices) {
      const ctx = document.getElementById("myChart");
      const myChart = new Chart(ctx, {
        type: "line",
        data: {
          labels: [prices[0].date],
          datasets: [
            {
              label: 'Dataset msft',
              data: prices[0].price
            },
            {
              label: 'Dataset google',
              data: prices[1].price
            }
          ]
        }
      });
    }
}

1πŸ‘

Here, a very basic example:

<script>
export default {
  async mounted() {
    await this.$nextTick();
    const ctx = document.getElementById("myChart");
    this.chart = new Chart(ctx, {
      type: "line",
      data: {
        labels: [],
        datasets: [],
      },
    });
  },
  data() {
    return {
      selected: "",
      chart: null,
      options: [
        { text: "msft", value: "msft" },
        { text: "GOOGL", value: "GOOGL" },
      ],
    };
  },
  watch: {
    selected: function () {
      this.getPrice();
    },
  },
  methods: {
    async getPrice() {
      let { data } = await axios.get("https://site/....");
      this.chart.data.datasets = [{ label: "dummy data" , data: [2, 3, 4]}];
      this.chart.data.label = [1, 2, 3];
      this.chart.update(); //very important, always update it
    },
  },
};
</script>

You create a property called chart and save your chart to it.

Then, after you fetch your data, you can access your chart with this.chart and then you set your datasets and labels. Whenever you make an change to the chart, use this.chart.update() to update it on the browser.

If you execute this code, you should see some dummy data in the chart

Leave a comment