首页 > 解决方案 > Vue.js 更新数组无法使用 this.$set

问题描述

我向服务发出请求并填充一个内部有多个数组的对象,它本身就是一个数组。前任:this.Jprojs: [{name : 'test', ListItem1 : [], ListItem2 : [] }]

我把那个对象放在一个 v-for 中:

<div id="app">
<table class="table table-striped">
  <tr>
    <th width="15%">Proj</th>
    <th>Detail</th>
  </tr>
  <tr v-for="proj in Jprojs" :key="proj.name">
    <td style="vertical-align:middle;"><strong>{{proj.name}}</strong><br/><a v-on:click="list(proj)"> <font-awesome-icon icon="tasks" /></a></td>
    <td>{{proj.ListItem1.length}}</td>
  </tr>
</table>

我有方法列表:

list : function(proj){
    axios.get(url).then(
      response => {
        this.$set(proj.ListItem1,0,response.data.value);
        //Vue.set(proj.ListItem1,0,response.data.value);
        this.nextTick;
        console.log(proj)
      },
      error => {
      },
      err => { }
    );
}

控制台显示更新,但 html 未更新。

标签: vue.jsvuejs2

解决方案


确保更新Jprojs值,而不是proj. 您可以传递索引而不是proj对象。

获取索引v-for="(proj, index) in Jprojs"并将其作为list(index). 然后只需编辑Jprojs具有给定索引的数组;Jprojs[index].ListItem1 = ...


推荐阅读