Miguel
Miguel

Reputation: 1897

Declaring dynamic data in a component, Vuejs 2

I'm begining now with vue js 2. I have this code, which receives dynamic data from the server (laravel 5.3 app), the problem is when i try to declare the users array on the component instead of declaring in the Vue() instance (in this case works great):

HTML:

<div id="app">
    <my-component>
        <ul id="users-list">
            <li v-for="user in users">{{user.name}}</li>
        </ul>
    </my-component>
</div>

JS:

Vue.component('my-component', {
    template: '#users-list',
    data: function () {
        return {
            users: []
        }
    },
    mounted: function() {
        this.$http.get('http://127.0.0.1:8003/api/test').then((response) => {
            console.log(response.body);
            this.users = response.body;
        }, function() {
            alert('brrh');
        });
    }
});
new Vue({
    el: '#app',
});

The error message: "Uncaught ReferenceError: users is not defined"

Upvotes: 1

Views: 11379

Answers (1)

Justin MacArthur
Justin MacArthur

Reputation: 4050

Looks like you're trying to do an inline-template try adding that directive to your <my-component> call.

    <div id="app">
            <my-component inline-template>
                    <ul id="users-list">
                            <li v-for="user in users">{{user.name}}</li>
                    </ul>
            </my-component>
    </div>

You will also have to remove the template parameter from your component call

    Vue.component('my-component', {
        data: function () {
            return {
                users: []
            }
        },
        mounted: function() {
            this.$http.get('http://127.0.0.1:8003/api/test').then((response) => {
                console.log(response.body);
                this.users = response.body;
            }, function() {
                alert('brrh');
            });
        }
    });

    new Vue({
            el: '#app',
    });

jsFiddle

Upvotes: 4

Related Questions