2017-06-29 81 views
0

我有一个表行,是以表行的值,并将其放入一个列表,然后我设置列表等于VUE阵列我这里是阵列jQuery的点击功能。 阵列:Vue的数组不更新

tableRow: [ 
       { 
        "name": "1", 
        "numSongs": "2", 
        "Year": "3" 
       } 
      ] 

功能:

$("#table1 tr").click(function() { 
     var list = []; 

     var $row = $(this).closest("tr"), 
      $tds = $row.find("td"); 

     list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() }); 
     this.tableRow = list; 
     console.log(this.tableRow); 
    }); 

我还记录列表的值当应用程序加载时,当我点击它,它确实发生了改变。 console output

然后我有一个函数来测试值是否已经改变了只是一个简单的警报功能。

greet: function() { 
      // `this` inside methods points to the Vue instance 
      alert('Hello ' + this.tableRow[0].name) 
     }, 

但该值不更新在函数中没有人知道为什么。

Vue的实例代码

export default { 

    data() { 
     return { 
      tableRow: [ 
       { 
        "name": "1", 
        "numSongs": "2", 
        "Year": "3" 
       } 
      ] 
     } 
    }, 
    mounted: function() { 
     console.log(this.tableRow); 
     this.$nextTick(() => { 
      $("#table1 tr").click(function() { 
       var list = []; 

       var $row = $(this).closest("tr"), 
        $tds = $row.find("td"); 

       list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() }); 
       this.tableRow = list; 
       console.log(this.tableRow); 
      }); 
     }); 
    }, 

    methods: { 
     greet: function() { 
      // `this` inside methods points to the Vue instance 
      alert('Hello ' + this.tableRow[0].name) 
     }, 
} 
} 
+0

你能告诉我它加入到这个问题刚才VUE实例代码 –

+0

。 – DanielM96

回答

3

这是由于this

在您单击处理范围界定问题,你正在做this.tableRow = list其中tableRow是数据选项的属性在VUE例如this不指向VUE实例,它指的是调用事件元件

所以像这样做:

mounted: function() { 
    var self = this; 
    console.log(this.tableRow); 
    this.$nextTick(() => { 
     $("#table1 tr").click(function() { 
      var list = []; 

      var $row = $(this).closest("tr"), 
       $tds = $row.find("td"); 

       list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() }); 
       self.tableRow = list; 
       console.log(this.tableRow); 
     }); 
    }); 
}, 
+0

这一工程谢谢 – DanielM96

+0

@ DanielM96乐于帮助:) –

+0

这里有一些额外的信息[使用Vue的“本”(https://stackoverflow.com/documentation/vue.js/9350/using-this-in- VUE#吨= 201706291623105439049) – thanksd