[Vuejs]-In Vue JS, assign data from mounted()

0👍

It is simple. You need to use arrow function inside mounted. The scope of this pointer is lost when you use normal function.

methods: {
    setSeries() {
        // Note the use of arrow function
        this.$setData(() => {
            this.chartOptions.series[1] = this.bsData[100000000];
        });
    }
}

Alternately, if you do not want to use arrow function, maintain reference to this pointer using closure:

methods: {
    setSeries() {
        // Maintain the closure
        const vm = this;

        this.$setData(function () {
            vm.chartOptions.series[1] = vm.bsData[100000000];
        });
    }
}

Further, there are two more problems with your code. The method $setData does not exist in Vue.js. You need to use $set method as documented here. So your code would be:

methods: {
    setSeries() {

        this.$set(() => {
            this.chartOptions.series[1] = this.bsData[100000000];
        });
    }
}

Next, you should not need to use $set method directly. It is meant to be used in corner cases. Vue.js detects changes automatically using getters and setters. Read more about array change detection here. For array, you must use wrapped methods or create new array each time.

So your final solution would be something like:

methods: {
    setSeries() {
        // Updating array data structure by creating new array instead of updating array by index.
        this.chartOptions.series = [this.chartOptions.series[0], this.bsData[100000000]];
    }
}

In summary you need to do three things:

  1. Use arrow function to maintain this reference.
  2. Do not use $set to change Vue instance data.
  3. Do not mutate array directly using index. Use methods like concat, wrapped methods like push, pop, etc. or de-structuring to create new array.

Leave a comment