0

I want to get data from Api service and show it in 'for loop' by VueJs.

But when I got data from Api service, Vue didn't update 'for loop'.

 <div v-for="item in messages">
       {{item}}
 </div>
 
 new Vue({
        el: '#main-content',
        data: {
            next: false,
            experts: <?php echo json_encode($list_of_expert_activity); ?>,
            activitys: null,
            messages: []
        },
        methods: {
            contract_message() {
                let url = '<?= URL ?>';
                let id = '<?= $data['contract_id'] ?>';
                axios.get(url + '/panel_admin/contract_message/' + id)
                    .then(function(response) {
                        this.messages = response.data
                        //Vue.set(this.message,)
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
                    .then(function() {
                        
                    });
            }
        }
    })

API Service response sample:

[
  {
    "id":1,
    "color":"red",
  },
   {
    "id":2,
    "color":"blue",
  }
]

1 Answers1

0

The problem with your code is this part:

.then(function(response) {
   this.messages = response.data
   //Vue.set(this.message,)
})

The this does not refer to the vue component here.

You can solve that by changing the callback function you pass to then to an arrow function:

.then((response) => {
   this.messages = response.data
   //Vue.set(this.message,)
})
t.niese
  • 39,256
  • 9
  • 74
  • 101