Vue数据引用问题

时间:2017-02-15 16:58:58

标签: vue.js

这很奇怪,因为它刚刚在昨晚工作,但基本上我有一个Vue应用程序从我的后端拉JSON。代码如下。奇怪的是,当loadData函数运行时,我看到了“已加载的数据”。控制台中的消息以及JSON中的项目列表,然后我收到一个控制台错误,说“项目未定义'”。我必须做一个微妙的错字或一些愚蠢的改变,但我无法在任何地方找到它!有什么想法吗?

HTML片段:

<div id="app">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Query</th>
                            <th>Initiated By</th>
                            <th>Type</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <div v-for="item in items">
                                <td>{{ item.id }}</td>
                                <td>{{ item.query }}</td>
                                <td>{{ item.user }}</td>
                                <td>{{ item.type }}</td>
                            </div>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

(然后<script src="app.js"></script>之前的</body>}

JS代码:

new Vue({
    el: '#app',
    data: {
        items: [],
        interval: null
    },
    methods: {
        loadData: function () {
            $.get('http://localhost:4567/getQueue', function (response) {
                this.items = response.results;
                console.log("Loaded data.")
                console.log(response.results)
            }.bind(this));
        }
    },

    created: function () {
        console.log("Loading data...")

        this.loadData();

        console.log(items)

        this.interval = setInterval(function () {
            this.loadData();
        }.bind(this), 3000); 
    },

    beforeDestroy: function(){
        clearInterval(this.interval);
    }
});

2 个答案:

答案 0 :(得分:0)

您收到错误

  

未定义项目

因为以下行:

created: function () {
    console.log("Loading data...")

    this.loadData();

    console.log(items)   <== this should be console.log(this.items)

答案 1 :(得分:0)

原来我的代码中存在一些问题。

1)正如Saurabh指出的那样,我忘记了this.items而不是items

2)this不能在我定义的函数内部引用,因为我拥有它...相反,函数必须用=>定义,例如:

$.get('http://localhost:4567/getQueue').then((response) => {
        this.items = response.data.results;
        console.log("loadData finished - items length is: "+this.items.length)
    })
3)我遇到的最大错误是我的div绑定项目是里面表格标签,这显然是不行的。相反,我将Vue绑定到现有标签(table,tr)。