我需要用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>
答案 0 :(得分:0)
您可以执行以下操作,而不是过滤和推送数据:
listen: function() {
var self = this
this.pusher.subscribe('expert-front', channel => {
channel.bind('edit', (data) => {
//Find the index of the item chag
let index = self.experts.findIndex((expert) => expert.id === data.id)
self.experts = [
...self.experts.slice(0, index - 1),
data,
...self.experts.slice(index + 1)
]
});
});
}
我希望有所帮助!