Vue笔记04 分页
coconutnut

https://www.bilibili.com/video/av85793766?p=4

表格与分页

在上一次的基础上添加表格和分页,在官网拷过来,放在Page1

注意不能直接并列放在template下,由于只能有一个根节点,外面要套一个div

表格数据加载

1
2
3
4
5
6
<el-table-column
fixed
prop="id"
label="编号"
width="150">
</el-table-column>
1
2
3
4
5
tableData: [{
id: '01',
name: '书籍1',
author: '作者1',
}

根据prop的值和数据对应

分页

1
2
3
4
5
<el-pagination
background
layout="prev, pager, next"
:total="1000">
</el-pagination>

total是总记录数,默认每页10条,此时就有1000/10=100页

绑定点击事件

用@current-change=”page”

1
2
3
4
5
6
<el-pagination
background
layout="prev, pager, next"
:total="100"
@current-change="clickPage">
</el-pagination>

Script中加

1
2
3
4
5
6
7
8
<script>
export default {
methods: {
clickPage(){
alert(1)
},
},
}

即可看到效果

点击翻页

把传过来的对象打印看看,发现就是页面的index

绑测试的数据试试,后面在连后台

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
clickPage(index){
switch(index){
case 1:
this.tableData = [{
id: '01',
name: '书籍1',
author: '作者1',
}, {
id: '02',
name: '书籍2',
author: '作者2',
}, {
id: '03',
name: '书籍3',
author: '作者3',
}]
break;
case 2:
this.tableData = [{
id: '04',
name: '书籍4',
author: '作者4',
}, {
id: '05',
name: '书籍5',
author: '作者5',
}, {
id: '06',
name: '书籍6',
author: '作者6',
}]
break;
}
},

可以正常切换

后端添加分页操作

Spring Boot的Repository把分页也解决了

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@SpringBootTest
class BookstoreServerApplicationTests {

@Autowired
BookRepository repository;

@Test
void contextLoads() {
PageRequest pageRequest = PageRequest.of(3,3);
Page<Book> page = repository.findAll(pageRequest);
System.out.println(page);
}

}

需要的东西都取出来了

直接调方法实现接口就可以了

在controller中,接收参数,调findAll,返回Page

1
2
3
4
5
@GetMapping("/findAll/{page}/{size}")
public Page<Book> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
PageRequest pageRequest = PageRequest.of(page,size);
return bookRepository.findAll(pageRequest);
}

对接

装插件

1
vue add axios

axio.get().then()

get里是请求,then里是回调函数

1
2
3
4
5
created(){
axios.get('http://localhost:8181/book/findAll/0/6').then(function(resp){
console.log(resp)
})
}

看到数据得到了

Page中data.content部分就是书籍数据,赋值即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data() {
return {
pageSize:'6',
total:'',
tableData:''
}
},
created(){
const _this = this
axios.get('http://localhost:8181/book/findAll/0/6').then(function(resp){
_this.tableData = resp.data.content
_this.pageSize = resp.data.size
_this.total = resp.data.totalElements
})
}
1
2
3
4
5
6
7
<el-pagination
background
layout="prev, pager, next"
:page-size="pageSize"
:total="total"
@current-change="clickPage">
</el-pagination>

并且修改点击事件绑定的函数

1
2
3
4
5
6
7
8
clickPage(index){
const _this = this
axios.get('http://localhost:8181/book/findAll/'+(index-1)+'/6').then(function(resp){
_this.tableData = resp.data.content
_this.pageSize = resp.data.size
_this.total = resp.data.totalElements
})
},

就可以点击翻页了