[Chartjs]-How to make dynamic chart using Vue component with chart-js

2👍

Using a computed property is not the best way to implement a bubble sort visualization, for two reasons:

  • The computed property is re-calculated every time a changes, and you are changing the value of a in the computed property itself; this is probably what causes the browser to hang.
  • There is no noticeable delay between executing the computed property function and updating the view, so the user won’t see any animation.

Since you are not using a directly in your template, and the computed property has only one dependency, a, get rid of the computed property, it’s not needed.

Instead, create a function that completes a single pass of the bubble sort algorithm, and call that function in a setInterval, cancelling the loop when a pass is made with 0 swaps:

export default {
  name: 'HelloWorld',
  data() {
    return {
      a : [12, 0, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213],
      intervalId: null,
    }
  },
  methods: {
    bubbleSort() {
      let swapped = false;

      for (let i = 0; i < this.a.length - 1; i++) {
        if (this.a[i] > this.a[i+1]) {
          const temp = this.a[i];
          this.$set(this.a, i, this.a[i+1]);
          this.$set(this.a, i+1, temp);
          swapped = true;
        }
      }

      if (!swapped) {
        clearInterval(this.intervalId);
      }
    },
  },
  mounted() {
    this.intervalId = setInterval(() => {
      this.bubbleSort();
    }, 2000);
  }
};

Notes:

  • Vue’s reactivity system won’t notice changes to arrays when accessing them via index, so $set must be used instead. See https://v2.vuejs.org/v2/guide/list.html#Caveats.
  • A bar chart will look nicer in this case than a line chart.
  • a is a very nondescript variable name, try to give it a more meaningful and unique name.
  • Be more precise than "browser hangs" when describing a bug. Does the browser window just freeze (i.e. can’t interact with the page)? How long does it take for that to happen? Are there errors in the console? Etc.
  • You have a typo in your question: swapp. Don’t be so lazy. If you don’t give a shit about your question, no one will give a shit about answering it.

Leave a comment