2016-01-22 121 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 = '' 
    },