代码之家  ›  专栏  ›  技术社区  ›  Eltyer

Vue v-for列表在数据更改后不更新

  •  1
  • Eltyer  · 技术社区  · 7 年前

    Vue实例从API加载组。 这些组使用v-for语法显示。

    groupdata格式正确,并添加到应用程序中。使用的组。push函数,该函数应更新v-for列表。

    但是,v-for列表不会更新。

    当我将v-for=“group in groups”(外部加载)更改为v-for=“group in people”(已经在应用程序中)时,它确实会给出输出。

    HTML

       <div id="app" class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Realtime Socket Chat</div>
                    <div class="panel-body" v-if="dataReady" v-for="group in groups"> @{{ group.name }}
                        <a v-bind:href="group.link" class="pull-right">
                            <div class="btn btn-xs btn-primary">
                                Join
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    

    Vue

    var app = new Vue({
        el: "#app",
        data: {
            groups: [],
            people: [{name: 'hi'}, {name: 'lol'}]
        },
        mounted: function() {
            this.load()
        },
        methods: {
            load: function() {
                axios.get('http://example.com/groups')
                    .then(function (response) {
    
                    console.log(response.data.groups);
    
                    response.data.groups.forEach(function(group) {
                        app.groups.push(group);
                    });
    
                    // app.groups.forEach(function (group) {
                    //    group.link = '/g/' + group.id + '/join';
                    // });
                    // console.log(response.data.groups);
    
                    console.log(this.groups); //outputs [{...}, {...}] so this.groups is good
                })
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }
    
    });
    

    美国石油学会

    {

    “组”:[ {

      "id": 1,
      "name": "Photography Chat",
      "created_at": "2017-11-26 08:50:16",
      "updated_at": "2017-11-26 08:50:16"
    },
    
    {
      "id": 2,
      "name": "Media Chat",
      "created_at": "2017-11-26 08:50:16",
      "updated_at": "2017-11-26 08:50:16"
    }
    

    ]

    }

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ikbel    7 年前

    看起来像是 app 当您的 load 负载 函数应如下所示:

    load: function() {
      axios.get('http://example.com/groups')
        .then(response => {    
          let groups = response.data.groups || []
    
          groups.forEach(group => {
            this.groups.push(group)
          })
    
          console.log(this.groups)
    
        })
        .catch(error => {
          this.errors.push(error)
          console.log(error)
        })
    }
    
        2
  •  0
  •   Eltyer    7 年前

    我在问题中遗漏了一个事实(因为我认为这无关紧要),那就是我在Laravel框架内工作,Laravel在main中自动导入VueJ。js。当另外加载Vue时,这并不能很好地发挥作用。我拆下了主电缆。js和它的工作。