1

I am trying to fill an array, declared in data property, by calling a function in methods property in Vue js. Here is the code:

<script>
export default {
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData, this.options);
    this.fillLabel();
  },
  data() {
    return {
      chartData: {
        labels:[],
        datasets: [
          {
            label: "Users",
            data: [40,20,12,39,10,40]
          }
        ]
      },

    };
  },
  methods: {
    fillLabel() {
      this.chartData.datasets[0].data.map(function (key,value) {
          this.chartData.labels.push(key);
      })

    }
  }
};
</script>

But this gives me following error in console :

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'chartData' of undefined"

So how can I fill the labels array(inside chatData) by 0 to length of data array(inside datasets).

I am looking for your help. Thanks in advance.

1
  • 1
    User arrow function to point the correct this :this.chartData.datasets[0].data.map((key,value)=>.... Commented Mar 25, 2020 at 6:44

2 Answers 2

1

This is due to the fact that your function inside your map function will loose the this context. and so its getting undefined.

to solve this problem use an arrow function inside your map.

this.chartData.datasets[0].data.map((key,value)=> { this.chartData.labels.push(key); })

this will solve the problem

Sign up to request clarification or add additional context in comments.

Comments

1

Only need to introduce this to your fillLabel method as below: I tried this solution nd it fixed the problem

fillLabel() {
            let th = this;
            th.chartData.datasets[0].data.map(function (key,value) {
                th.chartData.labels.push(key);
            })
            alert(th.chartData.labels)

        },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.