【问题标题】:Vue.js pagination componentVue.js 分页组件
【发布时间】:2017-11-08 01:25:11
【问题描述】:

我正在尝试制作一个通过 AJAX 调用执行分页的通用 Vue.JS 组件。我希望组件使用的数据(即项目列表)被组件封装,并且只有 AJAX URL 通过 Vue.JS Props 传递给组件。我正在使用 SLOT 来填充组件模板,包括迭代部分。 我认为这意味着父级(调用者)需要在迭代期间访问绑定变量,因为调用者正在循环遍历这些项目。我不能将循环部分放入组件中,因为组件特定于一种类型列表,不再是一般的列表了。

即使在使用 SLOT 时,如何让组件遍历项目。或者至少允许父级遍历项目但将数据传递给组件,以便它可以获取下一页并更新父母的数据。

为了更好的说明看下面的代码:

// my component
Vue.component('pagination', {
  template: '#pagination-component',
  props:  {
   // the URL for ajax calls is passed from parent to component
   source: {
      type: String,
      required: true
    }
 },
  data: function () {
    // access the data being paginated somehow
    return data;
  },

  created: 
     function () {
    console.log("component loaded...");
    this.getNextPage();
    },
  methods: 
  {
    getNextPage: function () {
          console.log("getNextPage called...");
          // call ajax method and populate the binded data 
    },
    getPrevPage: function () {
          console.log("getPrevPage called...");
          // call ajax method and populate the binded data    
    }
  }
})

console.log("javascript loaded...");


var app = new Vue({
     el: '#wrapper',
data: {    
}
})

我的组件布局是:

<script type="text/x-template" id="pagination-component">

<div class="pagination-wrapper">

<slot name="header"></slot>

<slot name="table">default text: Please define the table in parent!</slot>

<div class="well"> 
    <a href="#" @click="getPrevPage">Previous Page</a> | 
   <a href="#" @click="getNextPage">Next Page</a>
</div>

<slot name="footer"></slot>

</div>
</script>

而我使用该组件的主页(父)是:

<div class="table-wrapper" slot="table">

    <table class='table'>

         <tr>
             <th>Username</th>
             <th>First name</th>
             <th>Last name</th>
             <th>E-mail</th>
        </tr>

        <tr v-for="user in users">
          <td>
          <a :href="user.id">{{user.username}}</a>
          </td>
          <td>{{user.firstname}}</td>
          <td>{{user.lastname}}</td>
          <td>{{user.email}}</td>
        </tr>

    </table>

</div>

【问题讨论】:

    标签: javascript ajax pagination vue.js


    【解决方案1】:

    我意识到让分页器处理获取数据很诱人,但我认为最好的方法是让分页器与它正在分页的数据完全分离。

    因此,父级应该通过最大页数,并且分页器组件应该将页码发送回父级,然后父级应该根据该页码处理获取数据。这意味着您可以开发使用分页器的不同分页组件,而无需创建一个复杂的组件。

    实际上,几个月前我确实写了一些采用这种方法的东西,欢迎您在我的GitHub Page 上查看,虽然这个特定组件不稳定,但它应该让您了解我的意思。

    【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2016-04-25
    • 1970-01-01
    • 2019-11-04
    • 2021-07-13
    • 2019-11-16
    • 2021-01-24
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多