Vue+ElementUI实现用户管理前后分离实战一:前端篇

项目介绍

前几天有老铁问我能不能写一个Vue+ElementUI+SpringBoot后端的前后分离项目,最近有点忙,但今天他还是来了!希望对大家能有点帮助,大家还想要点啥也可以加我QQ或给我留言 :)

下一篇地址:
https://blog.csdn.net/IndexMan/article/details/112487012

用到的技术栈

界面布局和组件:Vue、ElementUI、Less
Ajax请求:axios
其他:sessionStorage
api接口:spring boot

实现效果展示


Vue+ElementUI实现用户管理前后分离实战一:前端篇_第1张图片
Vue+ElementUI实现用户管理前后分离实战一:前端篇_第2张图片

主要代码

这里只列几处重要代码,详细请看项目源码。

登录页

<template>
  <div class="login_container">
    <div class="login_box">
      
      <div class="avatar_box">
        <img src="../assets/logo.png"
             alt="avatar" />
      div>
      
      <div>
        <el-form ref="loginFormRef"
                 :model="loginForm"
                 :rules="loginFormRules"
                 label-width="60px"
                 class="login_form">
          <el-form-item label="账号"
                        prop="username">
            <el-input v-model="loginForm.username"
                      prefix-icon="iconfont icon-user">el-input>
          el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="loginForm.password"
                      type="password"
                      prefix-icon="iconfont icon-3702mima">el-input>
          el-form-item>
          <el-form-item class="btns">
            <el-button type="primary"
                       @click="login">登录el-button>
            <el-button type="info"
                       @click="resetLoginForm">重置el-button>
          el-form-item>
        el-form>
      div>
    div>
  div>
template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: "admin",
        password: "123456",
      },
      // 表单验证
      loginFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 表单重置按钮
    resetLoginForm() {
      // console.log(this)
      // resetFields:element-ui提供的表单方法
      this.$refs.loginFormRef.resetFields();
    },
    login() {
      // 表单预验证
      // valid:bool类型
      this.$refs.loginFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return false;
        // this.$http.post('login', this.loginForm): 返回值为promise
        // 返回值为promise,可加await简化操作 相应的也要加async
        const { data: res } = await this.$http.post("login", this.loginForm);
        console.log(res);
        if (res.code !== 200) return this.$message.error("登录失败");
        this.$message.success("登录成功");
        // 1、将登陆成功之后的token, 保存到客户端的sessionStorage中; localStorage中是持久化的保存
        //   1.1 项目中出现了登录之外的其他API接口,必须在登陆之后才能访问
        //   1.2 token 只应在当前网站打开期间生效,所以将token保存在sessionStorage中
        window.sessionStorage.setItem("token", res.data);
        // 2、通过编程式导航跳转到后台主页, 路由地址为:/home
        this.$router.push("/home");
      });
    },
  },
};
script>

用户列表页

<template>
  <div>
    
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页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="6">
          <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 type="index"
                         label="序号">el-table-column>
        <el-table-column prop="username"
                         label="用户名">el-table-column>
        <el-table-column prop="email"
                         label="邮箱">el-table-column>
        <el-table-column prop="mobile"
                         label="电话">el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       circle
                       @click="showEditDialog(scope.row.id)">el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       circle
                       @click="removeUserById(scope.row.id)">el-button>
          template>
        el-table-column>
      el-table>
      
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNo"
                     :page-size="queryInfo.pageSize"
                     layout="total, prev, pager, next, jumper"
                     :total="total">el-pagination>
    el-card>

    
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed">
      
      <el-form :model="addUserForm"
               ref="addUserFormRef"
               :rules="addUserFormRules"
               label-width="100px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addUserForm.username">el-input>
        el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addUserForm.password">el-input>
        el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addUserForm.email">el-input>
        el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addUserForm.mobile">el-input>
        el-form-item>
      el-form>
      <span slot="footer"
            class="dialog-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="editUserForm"
               ref="editUserFormRef"
               :rules="editUserFormRules"
               label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username"
                    disabled>el-input>
        el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editUserForm.email">el-input>
        el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="editUserForm.mobile">el-input>
        el-form-item>
      el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消el-button>
        <el-button type="primary"
                   @click="editUser">确 定el-button>
      span>
    el-dialog>

  div>
template>

<script>
export default {
  data() {
    return {
      // 获取用户列表查询参数对象
      queryInfo: {
        query: "",
        // 当前页数
        pageNo: 1,
        // 每页显示多少数据
        pageSize: 5,
      },
      userlist: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 用户添加
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 用户添加表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2~10个字",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "用户密码的长度在6~18个字",
            trigger: "blur",
          },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      },
      // 修改用户
      editDialogVisible: false,
      editUserForm: {},
      // 编辑用户表单验证
      editUserFormRules: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      },
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 当前需要被分配角色的用户
      userInfo: {},
      // 所有角色数据列表
      rolesLsit: [],
      // 已选中的角色Id值
      selectRoleId: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("user/list", {
        params: this.queryInfo,
      });
      if (res.code !== 200) {
        return this.$message.error("获取用户列表失败!");
      }
      this.userlist = res.data.records;
      this.total = res.data.total;
    },
    // 监听 pageSize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageNo = newSize;
      this.getUserList();
    },
    // 监听 添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      // 提交请求前,表单预验证
      this.$refs.addUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "user/modify",
          this.addUserForm
        );
        if (res.code !== 200) {
          this.$message.error("添加用户失败!");
          return;
        }
        this.$message.success("添加用户成功!");
        // 隐藏添加用户对话框
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 编辑用户信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("user/" + id);
      if (res.code !== 200) {
        return this.$message.error("查询用户信息失败!");
      }
      this.editUserForm = res.data;
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 修改用户信息
    editUser() {
      // 提交请求前,表单预验证
      this.$refs.editUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await this.$http.post("user/modify", {
          id: this.editUserForm.id,
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile,
        });
        if (res.code !== 200) {
          this.$message.error("更新用户信息失败!");
        }
        // 隐藏添加用户对话框
        this.editDialogVisible = false;
        this.$message.success("更新用户信息成功!");
        this.getUserList();
      });
    },
    // 删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm("确定删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      // 点击确定 返回值为:confirm
      // 点击取消 返回值为: cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.post("user/remove/" + id);
      if (res.code !== 200) return this.$message.error("删除用户失败!");
      this.$message.success("删除用户成功!");
      this.getUserList();
    },
  },
};
script>

<style lang="less" scoped>
style>

获取源码

喜欢的朋友给我点个赞,谢谢!

源码地址:
https://gitee.com/indexman/vue_element_user_demo

你可能感兴趣的