【问题标题】:How can I fill an array by calling a method in Vue js?如何通过调用Vue js中的方法来填充数组?
【发布时间】:2020-07-05 17:06:12
【问题描述】:

我正在尝试通过在 Vue js 中调用方法属性中的函数来填充在数据属性中声明的数组。代码如下:

<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>

但这在控制台中给了我以下错误:

[Vue 警告]:挂载钩子中的错误:“TypeError:无法读取未定义的属性 'chartData'”

那么如何将标签数组(chatData 内)填充为 0 到数据数组(数据集内)的长度。

我正在寻求您的帮助。提前致谢。

【问题讨论】:

  • 用户箭头函数指向正确的 this :this.chartData.datasets[0].data.map((key,value)=&gt;....

标签: vue.js vuejs2


【解决方案1】:

这是因为 map 函数中的函数会丢失 this 上下文。所以它变得不确定。

要解决这个问题,请在地图中使用箭头函数。

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

这样就可以解决问题了

【讨论】:

    【解决方案2】:

    只需将this 引入您的fillLabel 方法,如下所示: 我试过这个解决方案,它解决了问题

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

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多