替换对象数组vuejs

Replacing a array of objects vuejs

我需要用 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>

除了过滤和推送数据,您还可以这样做:

      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)
              ]
            });
        });
      }

希望对您有所帮助!