Vue循环列表 - 将ajax返回的数据附加到列表中?

时间:2017-12-25 08:31:00

标签: javascript jquery ajax vue.js

如何在ajax调用后附加vue列表?

这是我的Vue HTML:

     <a href="#" id="button-load" class="button button-load" data-posts-endpoint="...">Load More</a>

     <div id="news-posts">

        <!-- item -->
        <template v-for="item in items">
        <div class="cell large-4 medium-6">

            <!-- image has no padding -->
            <div class="card grid-item">
                <div class="card-divider">
                    <h4 class="heading heading-card"><a :href=item.url><span v-html=item.title></span></a></h4>
                </div>
                <div class="card-date">
                    <span v-html=item.date></span>
                </div>
                <div class="card-section"><p v-html=item.excerpt></p></div>
                <div class="text-right">
                    <a :href=item.url class="button button-more"><i class="material-icons">chevron_right</i></a>
                </div>
            </div>

        </div>
        <!-- item -->
        </template>
        <!-- vue - loop -->

    </div>

JS:

  // Render template with Vue.
  // Get json of catering menu.
  var element = document.getElementById('news-posts')
  var buttonLoad = document.getElementById('button-load')
  if (element !== null) {
    // var endpoint = $('#button-load').data('posts-endpoint') // jQuery
    var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
    var getData = await axios.get(endpoint)
    var cateringMenu = new Vue({
      el: '#news-posts',
      data: {
        items: getData.data
      }
    })
  }

  $("#button-load").click(function(){
    var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS
    $.get(endpoint, function(data, status){
        var cateringMenu = new Vue({
          el: '#news-posts',
          data: {
            items: data
          }
        })
    })
    return false
  })

当然,它不会将ajax返回的数据附加到列表中。

有什么想法吗?

修改

使用它:

  methods: {
    fetch: function (event) {
      var self = this
      // `this` inside methods points to the Vue instance
      $.ajax({
        url: endpoint,
        method: 'GET',
        success: function (data) {
          data.map(function(item) {
             self.items.push(item)
          })
        },
        error: function (error) {
          console.log(error)
        }
      })
    }
  }

1 个答案:

答案 0 :(得分:1)

您是否尝试让按钮执行在Vue中定义的方法,因此您可以访问该实例并可以使用this设置项目,如下所示;

methods: {
    fetch: function(){
        var endpoint = buttonLoad.getAttribute('data-posts-endpoint');
        $.get(endpoint, function(data, status){
            this.items = data; //set items.
        })
    }
}

然后将fecth方法添加到按钮中(需要在vue包装器中,在它看起来的外面)v-on:click.prevent="this.fecth"