2016-01-22 95 views
0

我玩弄vue.js和.vue組件,並作爲新手,我想知道如何跟蹤我添加到數組中的元素。跟蹤數組中添加的元素?

的情況如下:

  1. 用戶從一個形式
  2. 當他提交時,數據被自動添加到UL> li元素添加一個新的元件,以及POST請求時該API
  3. 當POST完成後,我想更新與來自服務器的新數據的特定華里。

事情是,我不能瞄準最後的李,因爲服務器可能需要時間來處理請求(他做了很多工作),所以用戶可能已經添加了1,5,10個其他項與此同時。

所以,我該怎麼辦?

這裏是我到目前爲止的代碼:

<template> 
    <form method="post" v-on:submit.prevent="search"> 
     <input type="text" placeholder="Person name" required v-model="name" v-el="nameInput" /> 
     <input type="text" placeholder="Company" required v-model="company" v-el="domainInput" /> 
     <input type="submit" value="Search" class="btn show-m" /> 
    </form> 
    <ul> 
     <li transition="expand" v-for="contact in contacts"> 
      <img v-bind:src="contact.avatar_url" width="40px" height="40px" class="cl-avatar" /> 
      <div class="cl-user"> 
       <strong class="cl-name">{{contact.name}} <span class="cl-company">{{contact.company}}</span></strong> 
      </div> 
     </li> 
    </ul> 
</template> 

<script> 
export default { 
    data() { 
     return { 
      contacts: [], 
      name: null, 
      company: null 
     } 
    }, 
    methods: { 
     search: function (event) { 
      this.$http.post('/search', { 
       name: this.name, 
       company: this.company 
      }).then(function (xhr) { 
       // HERE ! How can I target the exact entry ? 
       this.contacts.unshift(xhr.data) 
      }) 

      this.name = '' 
      this.company = '' 

      this.contacts.unshift({'name': this.name, 'company': this.company}) 
     }, 
    } 
} 
</script> 

謝謝您的幫助! :)

回答

0

我終於找到了一個工作的解決方案:我用一個組件,而不是<li />每個條目,管理組件內的這些狀態:

<ul> 
    <contact-entry v-for="contact in contacts" v-bind:contact="contact"></contact-entry> 
</ul> 

這樣,當我在陣列中添加新條目(描述d),製造了組件contact-entry的新實例。

該組件裏面,我做了以下內容:

<script> 
export default { 
    props: ['contact'], 
    created: function() { 
     if (this.contact.id === undefined) { // If it's a new contact 
      this.$http.post('search/name', { // I do the post here 
       name: this.contact.name, 
       domain: this.contact.company.name 
      }).then(function (xhr) { 
       this.contact = xhr.data // This will update the data once the server has replied, without hassle to find the correct line 
      }) 
     } 
    } 
} 
</script> 

這就是它! :)在父組件,我除去XHR請求和簡化的方法進行:

<script> 
export default { 
    data() { 
     return { 
      contacts: [], 
      name: null, 
      company: null 
     } 
    }, 
    methods: { 
     search: function (event) { 
      this.name = '' 
      this.company = '' 

      this.contacts.unshift({'name': this.name, 'company': this.company}) 
     } 
    } 
} 
</script> 
1

如果您知道namecompany領域是獨一無二的,你可以通過該數組找到它搜索...否則你可以等待其追加到數組,直到返回功能:

search: function (event) { 
     this.$http.post('/search', { 
      name: this.name, 
      company: this.company 
     }).then(function (xhr) { 
      this.contacts.unshift(xhr.data) 
     }) 

     this.name = '' 
     this.company = '' 
    },