【发布时间】: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