【发布时间】:2017-03-29 10:33:39
【问题描述】:
我需要用 vuejs 替换一个响应式对象数组, 我从 Api Restful 中检索数据,然后监听对象是否有变化。
例如,我得到了一个状态为(在线、离线、忙碌)的用户列表,如果用户更改了他们的状态,我需要更新已呈现的对象。
我找到的解决方案是找到并删除对象,然后推送新数据,但在这种情况下,我丢失了 DOM 中元素的顺序,因为新数据附加在最后:
<template>
<section>
<div v-for="expert in experts" :key="expert.id">
<div class="spinner" :class="expert.status"></div>
</div>
</section>
</template>
<script>
import axios from 'axios'
export default {
name: 'experts',
data: () => ({
experts: [],
errors: []
}),
// Fetches posts when the component is created.
created() {
axios.get(`http://siteapi.co/api/v1/users`)
.then(response => {
// JSON responses are automatically parsed.
this.experts = response.data.data
})
.catch(e => {
this.errors.push(e)
})
},
mounted() {
this.listen();
},
methods: {
listen: function() {
var self = this
//Listen if there is a status change
this.pusher.subscribe('expert-front', channel => {
channel.bind('edit', (data) => {
//Fid the object and deleted
self.experts = self.experts.filter(function (item) {
return item.id != data.id;
});
self.experts.push(data)
});
});
}
}
}
</script>
【问题讨论】:
-
您可以使用 for 循环将专家的索引存储在专家数组中,然后再将其删除。然后使用
self.experts.splice(index, 0, data)将新的专家对象插入到数组中的相同索引中
标签: vuejs2 vue-component