1. 程式人生 > >vuejs2.0 陣列操作 提示Cannot read property 'push' of undefined

vuejs2.0 陣列操作 提示Cannot read property 'push' of undefined

想做一個數組新增的操作
methods方法中

(rst.data.works.dataList).forEach(function(value,index){
          this.imglist.push(value);
       });

this.imglist 在data中定義的陣列

   data() {
      const self = this
      return {
        //作品陣列
        imglist: [],  
本來以為 定義了個全域性的self ,就可以用,但是還是報錯 push 未定義
發現沒有宣告this 指向的時候,this並不是指向的vue的,所以沒有找到this.imaglisyt 的push這個方法,自然就沒有push這個屬性了所以就必須 要設定 this的指向,
var _this=this;  //this指向vue 
 (rst.data.works.dataList).forEach(function(value,index){
      _this.imglist.push(value);
 })