在 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 中注意到日志消息之间存在细微差别:


第一个看起来像这样:{...}, ob : Se] 0: description: (...) name: (...)

第二个看起来更自然:[{…}] 0: description: "A nice pet" name: "Test pet"

这两者有区别吗?


胡说叔叔
浏览 239回答 2
2回答

守候你守候我

作为一种选择:var _results = [{name: 'toto', description: "titi" }];var app = new Vue({&nbsp; el: '#grid',&nbsp; data: {&nbsp; &nbsp; entries: _results&nbsp; }})socket.on('get_entries', function(data){&nbsp; &nbsp; console.log(_results);&nbsp;&nbsp; &nbsp; console.log(data);&nbsp; &nbsp; // Both logs show the same result (see below)&nbsp; &nbsp; _results[0].description = data[0].description&nbsp; &nbsp; // This works! The description of the 1st item is updated&nbsp; &nbsp; _results.splice(0, data.length, ...data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This doesn't work});

蛊毒传说

我相信有一种方法可以更新整个内容array,而无需做额外JavaScript的事情来触发反应,但使用Vue必须提供的东西。为此,您可能需要使用挂钩,以便我们可以使用socket来更新。created()arrow functionthisentries这样我们就data可以直接触发属性的反应。import io from 'socket.io-client';var _results = [{name: 'toto', description: "titi" }];var app = new Vue({&nbsp; el: '#grid',&nbsp; data: {&nbsp; &nbsp; entries: _results,&nbsp; &nbsp; socket: io()&nbsp; },&nbsp; created() {&nbsp;&nbsp; &nbsp;this.socket.on('get_entries', (data) => {&nbsp;&nbsp;&nbsp; &nbsp; this.entries = data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;});&nbsp; }})这也适用于您的情况吗?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript