2017-04-07 63 views
1

有没有适当的方法来刷新vueJS数组列表中的一个特定行而不重新加载所有数据?如何更新vueJs数组列表的特定行?

在这种情况下,它是一个电话列表。

<template> 
    <table class="table"> 
     <tr v-for="phone in phones"> 
      <td @click="edit(phone.id)"> 
       {{phone.number}} 
      </td> 
      <td class="pointerCursor" @click="edit(phone.id)"> 
       {{phone.comment | truncate(90)}} 
      </td> 
     </tr> 
    </table> 
</template> 

<script> 
    export default { 
     data() { 
      return { 
       phones = [ 
        {id:1, number: '001 656 88 44', comment:''}, 
        {id:2, number: '610-910-3575 x2750', comment:'Quod odit quia'}, 
        {id:3, number: '536.224.2639 x714', comment:'primary phone'}, 
        {id:5, number: '0034 556 65 77', comment:'home phone phone'}, 
       ] 
      } 
     }, 

     methods: { 
      edit(id) { 
       // update using an api that returns the updated data. 
       var updatedPhone = update(id) 

       // how to update with reloading all the phone list? 
       // ... 
      } 
     } 
    } 
</script> 

PS:这是一个代码,只是为了演示问题。

回答

3
const currentIndex = this.phones.findIndex(p => p.id === id); 
this.phones.splice(currentIndex, 1, updatedPhone) 

如果您的目标环境不支持数组上的findIndex,则可以使用其他方法查找当前索引。一个会通过电话,而不是它的ID。

edit(phone) { 
    const currentIndex = this.phones.indexOf(phone); 

    // update using an api that returns the updated data. 
    var updatedPhone = update(phone.id) 

    this.phones.splice(currentIndex, 1, updatedPhone) 
} 

在这两种情况下,Vue都会检测到变化并为您重新渲染。

+0

完美的作品。感谢:D – Warrio

1

你可以使用内置的指数代:

<tr v-for="(phone, index) in phones"> 
     <td @click="edit(index)"> 
      {{phone.number}} 
     </td> 
     <td class="pointerCursor" @click="edit(index)"> 
      {{phone.comment | truncate(90)}} 
     </td> 
    </tr> 

,然后在编辑功能:

methods: { 
     edit(index) { 
      phone = this.phones[index]; 

      // update using an api that returns the updated data. 
      var updatedPhone = update(phone.id) 

      // how to update with reloading all the phone list? 
      this.phones.splice(index, 1, updatedPhone) 
     } 
    }