0

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

Awar Pulldozer
  • 1,071
  • 6
  • 23
  • 40

1 Answers1

0

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)
 }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396