1

我需要观看一个 vue-resource HTTP 获取请求。如果找到新数据,我希望送到v-for循环,如果发现数据被删除,我想删除它而不重新渲染整个v-for数据。

JS

new Vue({
    el: '#chats',

    http: {
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    },

    data: {
        chats: []
    },

    watch: {
        /* 
        * I need to watch the 'chats' data
        * if found new data, I want that push it
        * if found data deleted I want to remove it
        */
    },

    methods: {
        indexChats: function() {

            /* vue-resource
            * I need to watch this http get data for changes
            */
            this.$http.get('/api/chats').then((response) => {
                this.$set('chats', response.json());

            }, (response) => {
                console.log('could not fetch chats from api');
            });
        }
    },

    ready: function() {
        this.indexChats();
    }
});

HTML

我想在不完全重新渲染整个v-for循环的情况下显示聊天。只需更新观察者发现的更改。

<ul id="chats">
    <li v-for="chat in chats">{{ chat.message }}</li>
</ul>
4

1 回答 1

4

您应该使用该track-by属性并使用chats模型中的唯一标识符。当数组更新时,Vue 将使用现有的渲染 DOM 来显示每个元素,而不是渲染新的 HTML。

<li v-for="chat in chats" track-by="id">{{ chat.message }}</li>

<li>如果现有的 HTML 具有相同的 id,则将用于呈现它。然后你只需要处理数组而不用担心渲染。

您不需要watch处理从该数组中插入和删除元素,它本质上由 Vue 监控。您只需编写检查是否已添加或删除项目的逻辑,以便您可以chats相应地更新。

于 2016-09-11T06:24:11.180 回答