0

I'm a beginner in VueJS so any help would be appreciated.

So I'm trying to display a list from my API. My API is working fine as I have tested it in Postman but when I try to create a list based on the response of my API, the list is not displayed. What am I doing wrong?

Here is my html:

<div id="tabs">
    <ul>
            <li v-for="user in users">
                {{ user.userid }}
            </li>
    </ul>
</div>

And here is my js:

var tabs = new Vue({
        el: '#tabs',
        data: {
            users: []
        },
        mounted: function(){
            this.getAllUsers()
        },
        methods: {
            getAllUsers: function(){
                axios.get('<?php echo base_url(); ?>users/all_users')
                .then(function(response){
                    this.users = response.data
                    console.log(this.users)
                })
            }
        }
})

Here is the screenshot of the console, the data are just for testing. value of users after getting response from API

Adrian
  • 327
  • 1
  • 5
  • 13

2 Answers2

2

In your axios "then" method, you write:

.then(function(response){
  this.users = response.data;
});

When using function keyword to declare a function, it creates its own context and therefore this value of its parent scope is not passed down to the function.

In Vue's case, this in the child function is not the intended Vue instance.

To solve this, simply pass the parent's this value to the callback, or use arrow functions.

Passing down using .bind

.then(function(response){
  this.users = response.data;
}.bind(this));

Using arrow function syntax

.then(response => {
  this.users = response.data;
});
yqlim
  • 6,898
  • 3
  • 19
  • 43
  • 1
    @Adrian Are you using PHP to embed javascript code right? then, I recommend you to use the `bind`, if you're not using a transpiler like Babel that code using array function won't work in all the browsers. Just a headsup! – Felipe Guizar Diaz Sep 18 '19 at 02:30
  • @FelipeGuizarDiaz Hi! No I'm not embedding javascript in PHP. Thanks for the headsup tho! – Adrian Sep 18 '19 at 02:49
0
<?php echo base_url(); ?>

I don't think this will be rendered in a js file. try hardcoding your baseURL instead. Example:

getAllUsers: function(){
    axios.get('http://app.test/users/all_users') // or axios.get('/api/users/all_users') if you're using an api based route for your api
    .then(function(response) {
         this.users = response.data
         console.log(this.users)
    })
}
japhfortin
  • 361
  • 4
  • 6
  • 18