【问题标题】:Replacing a array of objects vuejs替换一组对象vuejs
【发布时间】: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


【解决方案1】:

您可以执行以下操作,而不是过滤和推送数据:

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

希望对你有帮助!

【讨论】:

  • 谢谢@aks,这部分代码我不太理解:self.experts = [ ...self.experts.slice(0, index - 1), data, ... self.experts.slice(index + 1) ]
  • 这些是 ES2015 的新特性。所以我要做的是首先获取从 0 到索引 -1 的所有项目,然后我从索引 + 1 获取所有项目到最后。问题是 slice 将返回一个数组,因此最终结果可以变成一个数组数组,如 [[]、[]]。所以... 只是帮助压平价值
猜你喜欢
  • 2020-08-05
  • 2012-01-26
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2016-10-01
  • 2018-11-30
  • 2012-12-05
  • 2020-05-23
相关资源
最近更新 更多