3.8 el获取用户列表数据+翻页+查找用户
1. 直接从接口文档中获取
el-table中的:data="userList"
动态绑定一个对象数组,是从api接口中获得的。
el-table-column 中的prop="username"
继承userList
中的对象
<el-table :data="userList" style="width: 100%" border stripe>
<el-table-column type="index" label="#"></el-table-column>
//type="index"表示索引列
<el-table-column label="姓名" prop="username"></el-table-column>
<el-table-column label="邮箱" prop="email"></el-table-column>
<el-table-column label="电话" prop="mobile"></el-table-column>
<el-table-column label="角色" prop="role_name"></el-table-column>
</el-table>
从接口中获得userList代码如下:
{params: this.queryInfo}
这部分是在文档中要求请求需要带参数
data(){
return{
//获取用户列表的参数对象
queryInfo: {
query: '',
//当前页数
pagenum: 1,
//当前每页显示多少条数据
pagesize: 2
},
userList:[],
total:0
}
async getUserList(){
const {data: res} = await this.$http.get('users',{params: this.queryInfo})
if(res.meta.status !==200 )
return this.$message.error('获取用户列表失败!')
this.userList = res.data.users
this.total = res.data.total
console.log(res)
},
因为状态这一栏是一个开关,但在拿到的user数据中,这一栏mg_state
是一个布尔值
所以这里引入插槽来完成
scope作用域插槽,接收的是这一行的数据
打印{{scope.row}}
会得到这一整行的数据,那么再放入一个el开关来动态绑定scope.row.mg_state
并添加一个点击事件@change = "userStateChange(scope.row)"
,这个点击事件能够把前端改变的数值传回到数据库。这里用到了put方法。
代码如下:
<el-table-column label="状态" prop="mg_state">
<template slot-scope="scope">
<el-switch v-model="scope.row.mg_state" @change = "userStateChange(scope.row)">
</el-switch>
</template>
</el-table-column>
async userStateChange(userinfo){
console.log(userinfo)
const {data : res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
if(res.meta.status !== 200){
//如果更新失败就提示用户更新失败并重新对状态取反,从而状态未改变
userinfo.mg_state = !userinfo.mg_state
return this.$message.error('更新用户状态失败!')
}
this.$message.success('更新用户状态成功')
}
2.翻页
翻页的示意图所示
size-change
改变的是一页显示多少行,current-change
改变的是展示第几页。
page-sizes
是一个数组,表示下拉框:每页展示多少条
这有点不懂 这里的page-size
的数值就是框框中显示的数值,然后选择和于size-change
中的传入参数绑定。 。
current-page
同理
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="queryInfo.pagenum"
:page-sizes="[1, 2, 5, 10]"
:page-size="queryInfo.pagesize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
//监听 pagesize 改变事件
handleSizeChange(newSize){
console.log(newSize)
this.queryInfo.pagesize = newSize
this.getUserList()
},
//监听 页码值 改变时间
handleCurrentChange(newPage){
console.log(newPage)
this.queryInfo.pagenum = newPage;
this.getUserList()
//这里为什么是getuserlist 因为queryInfo.pagenum变了,可以重新请求数据渲染出来
},
3. 查找用户
clearable
代表可清空的
@clear="getUserList"
和@click="getUserList"
这两个事件都直接绑定的调用用户的这个函数,原因是:
query就是关键词搜索,这些都是后端做的,前端只用调用接口就可以
<el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
<el-button slot="append" icon="el-icon-search" @click="getUserList">
<!-- 搜索的算法是后端做的,所以只用调用接口就好 -->
</el-button>
</el-input>