为了账号安全,请及时绑定邮箱和手机立即绑定

在 Vue.js 中更新数据

在 Vue.js 中更新数据

胡说叔叔 2022-10-08 10:19:35
我正在尝试更新使用 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"这两者有区别吗?
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

作为一种选择:


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


});


查看完整回答
反对 回复 2022-10-08
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

我相信有一种方法可以更新整个内容array,而无需做额外JavaScript的事情来触发反应,但使用Vue必须提供的东西。


为此,您可能需要使用挂钩,以便我们可以使用socket来更新。created()arrow functionthisentries


这样我们就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;                                 

   });

  }

})

这也适用于您的情况吗?


查看完整回答
反对 回复 2022-10-08
  • 2 回答
  • 0 关注
  • 238 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号