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

im working with vuejs2 and laravel i have this vuejs2 code

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

also i have this html code

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

its working when there is no request send and showing me in the html 1 2 3 but when i have request back this code only working fine

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

but this one

this.test.push(4)

send me back this error

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

how can i add something to vuejs2 array thanks

1 answer

  • answered 2017-12-16 20:47 Sajeetharan

    You need to initialize it to empty array before pushing objects,

      this.test = [];
    

    EDIT

    When using arrow function, the this property is not overwritten and still references the component instance.

     success:(data) => {
        console.log(data[0]['id']);
        this.test.push(4)
     }