Laravel+vue-elementUI表格分页使用例子

16天前   阅读:122   分类:前端    标签: Vue

本文结合laravel和vue-element实现前端后端分页,包含增删改查搜索的实现,实现表单数据验证,非空判断。

效果展示

Laravel+vue-elementUI表格分页使用例子

1、编写后端laravel8接口代码,获取搜索条件,获取显示条数,获取当前页数

<?php
 
namespace App\Http\Controllers\Admin;
 
use App\Http\Common\Err\ApiErrDesc;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CheckUser;
use App\Http\Response\ResponseJson;
use App\Models\Admin\User;
use Illuminate\Http\Request;
 
class UserController extends Controller
{
    use ResponseJson;
    //用户列表
    public function index(Request $request){
        $where = [];
        if ($request->filled('query')) {
            $where[] = ['name','like','%'.$request['query'].'%'];
        }
        //获取条数
        $limit= $request->pagesize ?  $request->pagesize : 1;
        //获取当前页数
        $per_page= $request->pagenum;
        $columns = ['*'];
        $pageName = 'page';
 
        $res=User::where($where)->orderBy('id','desc')->paginate($limit, $columns, $pageName, $per_page)->toArray();
        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['stop'] = $v['stop']==0 ? true : false;
        }
        if($res){
            return $this->jsonData(ApiErrDesc::SUCCESS[0],ApiErrDesc::SUCCESS[1],$res);
        }else{
            return $this->jsonData(ApiErrDesc::ERROR[0],ApiErrDesc::ERROR[1],$res);
        }
 
    }
?>

2、vue前端el-table表格分页代码

<template>
    <div>
         <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
 
        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 搜搜与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="UserList" border stripe>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="账号" prop="name"></el-table-column>
                <el-table-column label="姓名" prop="realname"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="tel"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.stop" @change="userStateChanged(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                             <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible"  width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="账号" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="realname">
                    <el-input v-model="addForm.realname"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="tel">
                    <el-input v-model="addForm.tel"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible"  width="50%" @close="editDialogClosed" >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="账号" prop="name">
                <el-input v-model="editForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="editForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="realname">
                <el-input v-model="editForm.realname"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="tel">
                <el-input v-model="editForm.tel"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary"  @click="editUser">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

3、 数据处理代码

<script>
export default {
    data(){
        // 验证邮箱的规则
        var checkEmail = (rule, value, cb) => {
            // 邮箱正则表达式
            const regEmail =  /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if(regEmail.test(value)){
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }
 
         // 验证手机号的规则
        var checkTel = (rule, value, cb) => {
            const regTel = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
            if(regTel.test(value)){
                return cb()
            }
            cb(new Error('请输入合法的电话'))
        }
        return {
            // 获取用户列表的参数对象
            queryInfo: {
                query: '',
                // 当前的页数
                pagenum: 1,
                // 当前每页显示多少条数据
                pagesize: 10
            },
            UserList: [],
            total: 0,
            // 控制添加用户对话框的显示和隐藏
            addDialogVisible: false,
            //添加用户的表单数据
            addForm: {
                name: '',
                password: '',
                realname: '',
                email: '',
                tel: ''
            },
            //添加表单验证规则对象
            addFormRules: {
                name: [
                    {required: true, message: '请输入账号',trigger: 'blur'},
                    {min: 3, max:10, message: '账号的长度在3~10字符之间', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码',trigger: 'blur'},
                    {min: 6, max:15, message: '密码的长度在3~10字符之间', trigger: 'blur'}
                ],
                realname: [
                    {required: true, message: '请输入姓名',trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱',trigger: 'blur'},
                    {validator: checkEmail, trigger: 'blur'}
                ],
                tel: [
                    {required: true, message: '请输入电话',trigger: 'blur'},
                    {validator: checkTel, trigger: 'blur'}
                ]
            },
            // 控制修改用户对话框的显示和隐藏
            editDialogVisible: false,
            // 查询到用户信息对象
            editForm: [],
            //编辑表单验证规则对象
            editFormRules: {
                name: [
                    {required: true, message: '请输入账号',trigger: 'blur'},
                    {min: 3, max:10, message: '账号的长度在3~10字符之间', trigger: 'blur'}
                ],
                realname: [
                    {required: true, message: '请输入姓名',trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入邮箱',trigger: 'blur'},
                    {validator: checkEmail, trigger: 'blur'}
                ],
                tel: [
                    {required: true, message: '请输入电话',trigger: 'blur'},
                    {validator: checkTel, trigger: 'blur'}
                ]
            }
        }
    },
    created(){
        this.getUserList()
    },
    methods: {
        async getUserList(){
          const {data: res} = await this.$http.get('user',{params: this.queryInfo})
          if(res.code !=0){
              return this.$message.error('获取用户列表失败');
          }
        //   console.log( res.data.current_page)
          this.UserList = res.data.data
          this.total = res.data.total
          this.queryInfo.pagenum =res.data.current_page
        
        },
        // 监听 pagesize 改变事件
        handleSizeChange(newSize){
            // console.log(newSize)
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 监听页面值改变的事件
        handleCurrentChange(newPage){
            // console.log(newPage)
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 监听switch开关状态的改变
        async userStateChanged(userInfo){
            // console.log(userInfo);
            const {data: res} = await this.$http.post(`user/edit?id=${userInfo.id}&stop=${userInfo.stop}`)
            if(res.code !=101){
                userInfo.stop = !userInfo.stop
                return this.$message.error(res.msg);
            }
            return this.$message.success(res.msg);
        },
        // 监听添加用户对话框关闭时间
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        // 点击按钮添加新用户
        addUser(){
            this.$refs.addFormRef.validate(async valid => {
               if(!valid){
                   return;
               }
            //    发起添加用户网络请求
                const {data: res} = await this.$http.post('user/add',this.addForm)
                if(res.code!=103){
                    return this.$message.error(res.msg);
                }
                this.$message.success(res.msg);
                // 隐藏添加用户对话框
                this.addDialogVisible = false
                // 重新获取用户列表数据
                this.getUserList();
            })
        },
        // 展示编辑用户对话框
        async showEditDialog(id){
            const {data: res} = await this.$http.get('user/userEdit?id='+id)
            if(res.code !=0){
                return this.$message.error(res.msg);
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 监听编辑用户对话框关闭时间
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        // 点击按钮编辑用户
        editUser(){
            this.$refs.editFormRef.validate(async valid => {
               if(!valid){
                   return;
               }
 
            //    发起编辑用户网络请求
                const {data: res} = await this.$http.post('user/update?id='+this.editForm.id,this.editForm)
                if(res.code!=101){
                    return this.$message.error(res.msg);
                }
                this.$message.success(res.msg);
                // 隐藏编辑用户对话框
                this.editDialogVisible = false
                // 重新获取用户列表数据
                this.getUserList();
            })
        },
        // 根据id删除对应的用户信息
        async removeUserById(id){
            // 询问用户是否删除数据
           const confirmResult = await this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }
                ).catch(err => err)
                    if (confirmResult !='confirm'){
                        return this.$message({ type: 'info', message: '已取消删除'});
                    }
                            
                const {data: res} = await this.$http.post('user/del?id='+id)
                if(res.code!=106){
                    this.$message.error(res.msg)
                }
                 this.$message.success(res.msg)
                 this.getUserList();
                // console.log(confirmResult);
        }
    }
}
</script>
 
<style scoped>
 
</style>

4、main.js全局代码

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './plugins/element.js'
 
import axios from 'axios'
// 配置请求的更路径
global.domain = 'http://www.laravel8.com/api/';
axios.defaults.baseURL = domain
axios.interceptors.request.use(config=>{
  config.headers.token = window.sessionStorage.getItem('token')
  return config;
})
 
Vue.prototype.$http = axios
Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
  router,
  render: function (h) { return h(App) }
}).$mount('#app')

以上是个简单案例例子,供大家参考。

【腾讯云】11.11 云上盛惠,云产品限时抢购,1核2G云服务器首年88元

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/fdetail/507.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

上一篇:没有更多了文章

下一篇: TP5搜索分页

文章评论(0)

登录
简忆博客壁纸 头像

简忆博客
仕而优则学,学而优则仕。

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×