更新 Vue.js 中的数据

Updating data in Vue.js

我正在尝试更新使用 Vue.js 制作的数据网格,但内容没有正确更新。这是我的 HTML:

<div class="col-md-10 col-10">
    <div class="row" id="grid">
        <div class="col-md-4" v-for="entry in entries">
            <div class="info_overlay">
                <div>
                    <span class="name">{{ entry.name }}</span>
                    <span class="description">{{ entry.description }}</span>
                </div>
            </div>
        </div>
    </div>
</div>

现在这是我的 JS:

var _results = [{name: 'toto', description: "titi" }];
var app = new Vue({
  el: '#grid',
  data: {
    entries: _results
  }
})

socket.on('get_entries', function(data){
    console.log(_results); 
    console.log(data);
    // Both logs show the same result (see below)

    _results[0].description = data[0].description    // This works! The description of the 1st item is updated
    _results = data;                                 // This doesn't work

});

现在我不知道为什么不能一次更新整个数组。尽管数据相同,但我在 Chrome 中确实注意到日志消息之间存在细微差别:

这两个有区别吗?

我相信有一种方法可以更新整个 array 而无需执行额外的 JavaScript 来触发反应,但使用 Vue 必须提供的功能。

为此,您可能需要将 socket 放入带有 arrow functioncreated() 挂钩中,以便我们可以使用 this 更新 entries

这样我们就可以直接在 data 属性 上触发反应。

import io from 'socket.io-client';
var _results = [{name: 'toto', description: "titi" }];
var app = new Vue({
  el: '#grid',
  data: {
    entries: _results,
    socket: io()
  },
  created() { 
   this.socket.on('get_entries', (data) => {  
    this.entries = data;                                 
   });
  }
})

你的情况也适用吗?

作为一个选项:

var _results = [{name: 'toto', description: "titi" }];
var app = new Vue({
  el: '#grid',
  data: {
    entries: _results
  }
})

socket.on('get_entries', function(data){
    console.log(_results); 
    console.log(data);
    // Both logs show the same result (see below)

    _results[0].description = data[0].description    // This works! The description of the 1st item is updated
    _results.splice(0, data.length, ...data);                                // This doesn't work

});