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

浏览690

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

效果展示

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

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表格分页代码

             
                首页        用户管理        用户列表         
        
                    
                                                                                                                                                添加用户                                        
                                                                                                                                                                                                                                                                                                                                                                                                                         
                                                
                    
                                                                                                                                                                                                                                                                                                        
                            取 消                确 定                            
                                                                                                                                                                                                                                                    取 消            确 定

3、 数据处理代码

 {
            // 邮箱正则表达式
            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);
        }
    }
}" _ue_custom_node_="true">

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')

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


  • 暂无任何回答