我正在使用 vue.js 和 .vue 组件,作为新手,我想知道如何跟踪我在数组中添加的元素。
情况如下:
- 用户从表单添加新元素
- 当他提交时,数据会自动添加到 ul>li 元素中,并向 API 发出 POST 请求
- POST 完成后,我想用服务器上的新数据更新特定的 li。
问题是,我无法定位最后一个 li,因为服务器可能需要时间来处理请求(他做了很多工作),因此用户可能同时添加了 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>
感谢您的帮助! :)
最佳答案
如果您知道 name
和 company
字段是唯一的,您可以搜索数组来找到它...否则您只需等待将其附加到数组直到返回函数:
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 = ''
},
关于javascript - 跟踪数组中添加的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941770/