在组件中声明动态数据

Declaring dynamic data in a component, Vuejs 2

本文关键字:动态 数据 声明 组件      更新时间:2023-09-26

我现在从vue js 2开始。我有这段代码,它从服务器(laravel 5.3应用程序)接收动态数据,问题是当我试图在组件上声明用户数组而不是在Vue()实例中声明(在这种情况下工作得很好):

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',
});

错误信息:"Uncaught ReferenceError: users is not defined"

看起来你正在尝试做一个inline-template尝试将该指令添加到你的<my-component>调用。

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

你还必须从你的组件调用

中删除模板参数
    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