未捕获的TypeError:无法读取Object.success中未定义的属性'push'[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在使用vuejs2和laravel我有这个vuejs2代码

var path = '/project/public/';
new Vue({
el:'#users',
data:{
    message:'',
    test: [1,2,3],  
},
methods:{
    searchData: _.debounce(function(){
        if(this.message != '')
        {
            $.ajax({
                type:'POST',
                url: path+'usersearch',
                data: {data:this.message},
                success:function(data)
                {
                    console.log(data[0]['id']);
                      this.test.push(4)
                },
                error:function()
                {
                    console.log("error");
                }
            });
        }
    },1000)
}
})

我也有这个HTML代码

<tr>
    <td v-for='test in test'>@{{test}}</td>
</tr>

它的工作时没有请求发送并显示我在html 1 2 3,但当我有请求回来这个代码只能正常工作

console.log(data[0]['id']);

但这一个

this.test.push(4)

发回给我这个错误

Uncaught TypeError: Cannot read property 'push' of undefined     at Object.success

我怎么能添加一些东西到vuejs2数组谢谢

javascript html arrays vue.js vuejs2
1个回答
0
投票

在推送对象之前,需要将其初始化为空数组,

  this.test = [];

编辑

使用箭头函数时,不会覆盖此属性,仍会引用组件实例。

 success:(data) => {
    console.log(data[0]['id']);
    this.test.push(4)
 }
© www.soinside.com 2019 - 2024. All rights reserved.