SpringBoot+Vue实现简单用户管理平台第二篇(前端设计,接口对接)

SpringBoot+Vue实现简单用户管理平台第二篇(前端设计,接口对接),第1张

🚀 注重版权,转载请注明原作者和原文链接🥭 作者:Yuan-Programmer🍎 主页:https://blog.csdn.net/weixin_47971206/article/details/121368075?spm=1001.2014.3001.5502🍉 进来的小伙伴点点赞呀

本案例第一篇后端教学地址:https://blog.csdn.net/weixin_47971206/article/details/124741442?spm=1001.2014.3001.5501

demo地址预览:http://xiaoyuan-boke.com/user-manager

🚀 花了几个小时做了一个SpringBoot+Vue的简单用户管理demo项目,适合新手教程,项目已在Gitee上开源,Gitee开源地址:https://gitee.com/yuandewei/Yuan-SpringBoot/tree/master

Gitee上开源的代码跟本次的案例的代码有些区别,本次案例稍微改了一点点,不过不影响Gitee上的项目运行,大致效果如下,功能可以访问demo地址测试哦


话不多说,下面跟着我一步一步来吧~

前言

说实话,我个人觉得像这种的简单的crud项目前端比后端要麻烦多,也做的比后端慢

开发前准备 VSCode开发工具,很方便,推荐使用,你用其他前端编译器也没有问题(我之前出过安装教程)Vue环境的搭建,一个 node.js(我之前也出过安装教程,可以翻翻),一个 vue-cli 脚手架(网上很多教程),只要 node.js 成功安装配置没问题,脚手架安装很快的打开我们的 element ui 网站,地址:https://element.eleme.cn/#/zh-CN/component/installation打开 axios 官方网站,地址:http://www.axios-js.com/docs/ 🍒 脚手架创建项目,安装依赖

提一嘴,VSCode记得要安装Vue环境的插件,这个百度也有很多教程,就不介绍啦,还有就是要有一定Vue基础知识,至少了解vue的语法

创建项目

首先以管理员模式打开我们的 VSCode 工具,选择文件夹位置(待会创建项目的地方)

在下面终端输命令 vue create user-manager-vue 后面那个是项目名称,下面没有终端控制台的可以点击上面新建终端

选择 default 默认配置就好,我这里创建过做过配置,有自己单独的配置选项,你们第一次创建的选择默认的就行,然后等待创建完成

如图,一个脚手架的项目就创建好啦

我们什么都不做,先运行看看默认项目的样子吧,输入命令 cd user-manager-vue 跳转到项目目录下,接着输入 npm run serve 启动项目

显示如图,则启动成功,打开网站看一下

效果如图,这是脚手架创建项目的默认模板

安装依赖

回到编译器,ctrl c 结束运行,输入命令 npm i element-ui -S 安装element ui,接着输入命令 npm install axios 安装axios,用于向后端发送请求

🍅 初始配置,封装axios请求

修改main.js,加上下面五行代码,全局使用

import ElementUI from 'element-ui';
import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);
Vue.prototype.$axios = axios
封装请求

在 src 目录下新建 utils 文件夹,文件夹下新建 request.js 文件,代码内容我已经写有注释

import axios from 'axios'
import { Message } from 'element-ui'

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:8081", // 后端接口地址前缀(端口和后端配置文件一致)
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    // 请求头携带我们的权限码,和后端一致就行
    config.headers['Authentication'] = "dwagfhwhgiawpfwabifpjwaidjwaidwiafihwigfhwaigwhaipgwaihiwahifhwdefef"
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      /**
       * 可以自定义返回状态码,处理不同的结果
       */
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
修改app.vue

修改成下面这样

<template>
  <div id="app">
    <router-view>router-view>
  div>
template>

<style>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
style>
修改views文件夹

删除原来的 Home.vue 和 About.vue ,新建 index.vue,作为左侧导航栏组件(看demo地址效果)

再分别新建三个页面 userList.vue、addUser、userInfoList.vue,三个页面分别对应左侧导航栏展开的三个页面

接着在 index.vue 添加代码,

<template>
  <div class="app">
    <el-container style="height: 700px; border: 1px solid #eee">
      
        <el-aside width="200px"
                  style="background-color: rgb(238, 241, 246)">
            <el-menu router="router" :default-openeds="['0']">
                <el-submenu v-for="(item,index) in $router.options.routes"
                            :key="index"
                            :index="String(index)">
                    <template slot="title"><i :class="item.class">i>{{item.name}}template>
                    <el-menu-item v-for="(item1,index1) in item.children"
                                  :key="String(index1)"
                                  :index="item1.path"
                                  v-if="!(item1.hidden)"
                                  :class="$router.path==item1.path?'is-active':''">{{item1.name}}el-menu-item>
                el-submenu>
            el-menu>
        el-aside>

        
        <el-container>
            <el-header style="text-align: right; font-size: 12px">
                <el-dropdown>
                    <i class="el-icon-setting"
                       style="margin-right: 15px">i>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>功能一el-dropdown-item>
                        <el-dropdown-item>功能二el-dropdown-item>
                        <el-dropdown-item>功能三el-dropdown-item>
                    el-dropdown-menu>
                el-dropdown>
                <span>管理员span>
            el-header>

            
            <el-main>
                <router-view />
            el-main>
        el-container>
    el-container>
  div>
template>

<script>

export default {
}
script>

样式参考 element ui 的布局组件,下面有详细的属性说明哦

接着在另外三个页面先随便写点东西,输入


修改router路由

修改 router 文件夹下的 index.js,主要改两个地方,我直接全部代码粘贴出来

import Vue from 'vue'
import VueRouter from 'vue-router'
import index from '../views/index.vue'

Vue.use(VueRouter)

const routes = [
  {
		path: "/",
		name: "用户管理",
		component: index,
    class: 'el-icon-s-custom',
		children: [
			{
				path: "/",
				name: "数据列表",
				component: () => import("../views/userList.vue")
			},
      {
				path: "/addUser",
				name: "添加用户",
				component: () => import("../views/addUser.vue")
			},
      {
				path: "/editUser/:id",
				name: "编辑用户",
				component: () => import("../views/addUser.vue"),
        hidden: true //隐式路由
			},
			{
				path: "/userInfo",
				name: "用户信息",
				component: () => import("../views/userInfoList.vue")
			}
		],
	},
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

简要说明一下,children列表里面的是二级路由,外面的是一级路由

初始 *** 作做完了,先运行看看效果 npm run serve,看到图片的效果说明已经OK了

封装API接口

src文件夹下新建 api 文件夹,文件夹下新建 user.js,封装和后端对接的接口请求

import request from '../utils/request'

export default {

  // 添加用户接口
  addUser(user) {
    return request({
      url: '/user',
      method: 'post',
      data: user
    })
  },

  // 删除用户接口
  deleteUser(id) {
    return request({
      url: `/user/${id}`,
      method: 'delete'
    })
  },

  // 删除多个用户接口
  deleteMoreUser(ids) {
    return request({
      url: '/user',
      method: 'delete',
      data: ids
    })
  },

  // 编辑用户接口
  updateUser(user) {
    return request({
      url: `/user`,
      method: 'put',
      data: user
    })
  },

  // 查询用户列表接口
  findUserList(index,size, queryParam) {
    return request({
      url: `/user/${index}/${size}`,
      method: 'post',
      data: queryParam
    })
  },

  // 根据用户编号获取用户信息接口
  getUserInfo(id) {
    return request({
      url: `/user/${id}`,
      method: 'get'
    })
  }
}
🌲 用户信息页面

我们先来实现这个页面的功能,相对简单一点,就一个查询的 *** 作,页面模板在element ui这个位置

我们复制下面给出来的源码,粘贴到 userInfoList.vue 页面的 < div class=app>粘贴到这里< /div>

稍做修改,改成我们需要的格式

<div class="app">
      <el-descriptions class="margin-top"
                       title="小袁同学"
                       :column="3"
                       size="medium"
                       border>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user">i>
            用户名
          template>
          xiaoyuan
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone">i>
            手机号
          template>
          12345678910
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-check">i>
            性别
          template>el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets">i>
            注册时间
          template>
          2022-05-06 23:56:37
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-edit-outline">i>
            个人描述
          template>
         我性格开朗,希望和你交个朋友哦
        el-descriptions-item>
      el-descriptions>
    div>

在 created 周期函数给后端发送请求,我们打印一下看看数据格式

🔥 注意!记得启动后端的项目,同时controller控制层加上跨域注解,上一篇教程忘记加了

<script>
// 引入接口
import user from '../api/user'

export default {
  data() {
    return {
      // 用户信息列表
      userList: [],
    }
  },
  created() {
    // 发送请求,获取用户信息列表
    user.findUserList(1, 10).then((res) => {
      // 赋值
      this.userList = res.data.userList
      console.log(this.userList)
    })
  },
}
</script>

保存代码打开浏览器刷新,成功看到数据

最后加上分页组件,通过 v-for 标签遍历用户列表显示到页面上,代码有注释,完整代码如下

<template>
  <div class="app">
    <div :class="index > 0 ? 'info' : ''" v-for="(item, index) in userList" :key="index">
      <el-descriptions class="margin-top"
                       :title="item.nickname"
                       :column="3"
                       size="medium"
                       border>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user">i>
            用户名
          template>
           {{ item.username }}
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone">i>
            手机号
          template>
           {{ item.phone }}
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-check">i>
            性别
          template>
          {{ item.sex === '0' ? '男' : '女' }}
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets">i>
            注册时间
          template>
          {{ item.createTime }}
        el-descriptions-item>

        
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-edit-outline">i>
            个人描述
          template>
        {{ item.describe }}
        el-descriptions-item>
      el-descriptions>
    div>

    
    <div class="block"
         style="text-align:center;margin-top:10px;">
      <el-pagination background
                     @current-change="handleCurrentChange"
                     :current-page.sync="pageParam.index"
                     :page-size="pageParam.size"
                     :total="pageParam.total"
                     layout="prev, pager, next, jumper">
      el-pagination>
    div>
  div>
template>

<script>
// 引入接口
import user from '../api/user'

export default {
  data() {
    return {
      // 用户信息列表
      userList: [],
      // 分页
      pageParam: {
        index: 1,
        size: 4,
        total: 0,
      },
    }
  },
  methods: {
    // 切页
    handleCurrentChange(index) {
      this.pageParam.index = index
      this.getUserList()
    },
    getUserList() {
      // 发送请求,获取用户信息列表
      user.findUserList(this.pageParam.index, this.pageParam.size).then((res) => {
        // 赋值
        this.userList = res.data.userList
        // 总数赋值
        this.pageParam.total = res.data.total
      })
    }
  },
  created() {
    this.getUserList()
  },
}
script>

<style>
.info {
  margin-top: 20px;
}
style>

代码量也不多,保存浏览器刷新看效果,成功显示,切页正常

🌳 数据列表页面

这部分稍微难一点,内容比较多,我拆开来一部分一部分介绍,首先能显示用户列表,右侧加上编辑和删除按钮,在 element ui寻找合适的模板

想直接看结果跳过过程的,可以拉到本标题的末尾,有这页面的完整代码


然后做点修改,先能让数据显示出来,这部分和上面那个差不多的,没有难度

<template>
  <div>
    
    <el-table ref="multipleTable"
              :data="userList"
              border
              style="width: 100%">

      <el-table-column type="selection"
                       width="55">
      el-table-column>

      
      <el-table-column label="编号"
                       width="50">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}span>
        template>
      el-table-column>

      
      <el-table-column label="用户名"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}span>
        template>
      el-table-column>

      
      <el-table-column label="昵称"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}span>
        template>
      el-table-column>

      
      <el-table-column label="性别"
                       width="60">
        <template slot-scope="scope">
          <span>{{ scope.row.sex ===  '0' ? '男' : '女' }}span>
        template>
      el-table-column>

      
      <el-table-column label="手机号码"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}span>
        template>
      el-table-column>

      
      <el-table-column label="密码"
                       width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.password }}span>
        template>
      el-table-column>

      
      <el-table-column label="注册时间"
                       width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.gmtCreate }}span>
        template>
      el-table-column>

      
      <el-table-column label="描述"
                       width="auto">
        <template slot-scope="scope">
          <span>{{ scope.row.describe }}span>
        template>
      el-table-column>

      <el-table-column align="center"
                       label=" *** 作"
                       width="150">
        <template slot-scope="scope">
         
          <el-button size="mini"
                      type="warning"
                      icon="el-icon-edit">el-button>
          
          <el-button style="margin-left: 10px;"
                     size="mini"
                     type="danger"
                     icon="el-icon-delete">el-button>
        template>
      el-table-column>
    el-table>

    
    <div class="block"
         style="text-align:center;margin-top:10px;">
      <el-pagination background
                     @current-change="handleCurrentChange"
                     :current-page.sync="pageParam.index"
                     :page-size="pageParam.size"
                     :total="pageParam.total"
                     layout="prev, pager, next, jumper">
      el-pagination>
    div>

  div>
template>

<script>
import user from '../api/user'

export default {
  data() {
    return {
      // 分页
      pageParam: {
        index: 1,
        size: 10,
        total: 0,
      },
      // 数据
      userList: [],
    }
  },
  methods: {
    // 切页
    handleCurrentChange(index) {
      this.pageParam.index = index
      this.findUserList()
    },
    // 查询用户列表
    findUserList() {
      user.findUserList(this.pageParam.index, this.pageParam.size, this.queryParam).then((res) => {
        this.userList = res.data.userList
        this.pageParam.total = res.data.total
      })
    },
  },
  created() {
    this.findUserList()
  },
}
script>

效果如图

删除和一键删除

单个删除,在删除按钮标签加上点击触发函数,传递用户ID参数

接着在 methods: 里加上删除方法

// 删除单个用户
    deleteUser(id) {
      this.$confirm('此 *** 作将删除改用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 调用删除接口
        user.deleteUser(id).then((_) => {
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.findUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },

一键删除呢在表格标签加上一个属性,再加上一个按钮,属性这些在 element ui组件最下面都有详细的介绍

添加两个变量值,两个方法

保存刷新浏览器,效果如下,测试成功

多条件查询

在 element ui 的表单组件找到合适的,咋们多加个查询条件框


添加条件对象参数,一个提交查询方法,一个清空表单的方法

完整代码如下,我在编辑按钮加了路由跳转,这个待会做完添加用户功能再回来说

<template>
  <div class="app">
    
    <div>
     <el-form :inline="true" :model="queryParam" class="demo-form-inline" ref="queryParam">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParam.username" placeholder="输入用户名">el-input>
        el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="queryParam.nickname" placeholder="请输入昵称">el-input>
        el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="queryParam.phone" placeholder="请输入手机号码">el-input>
        el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="queryParam.sex" placeholder="选择性别">
            <el-option label="" value="0">el-option>
            <el-option label="" value="1">el-option>
          el-select>
        el-form-item>

        <el-form-item label="注册时间" prop="time">
          <el-date-picker v-model="queryParam.time"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择注册时间">
          el-date-picker>
        el-form-item>

        <el-form-item>
          <el-button type="primary"
                     icon="el-icon-search"
                     @click="submitSearch()">查询el-button>
        el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh"
                     @click="clearForm('queryParam')">重置el-button>
        el-form-item>
        <el-button v-if="more"
                   type="danger"
                   icon="el-icon-delete"
                   @click="deleteMore()">一键删除el-button>
      el-form>
    div>

    
    <el-table ref="multipleTable"
              :data="userList"
              border
              @selection-change="handleSelectionChange"
              style="width: 100%">

      <el-table-column type="selection"
                       width="55">
      el-table-column>

      
      <el-table-column label="编号"
                       width="50">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}span>
        template>
      el-table-column>

      
      <el-table-column label="用户名"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}span>
        template>
      el-table-column>

      
      <el-table-column label="昵称"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}span>
        template>
      el-table-column>

      
      <el-table-column label="性别"
                       width="60">
        <template slot-scope="scope">
          <span>{{ scope.row.sex ===  '0' ? '男' : '女' }}span>
        template>
      el-table-column>

      
      <el-table-column label="手机号码"
                       width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}span>
        template>
      el-table-column>

      
      <el-table-column label="密码"
                       width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.password }}span>
        template>
      el-table-column>

      
      <el-table-column label="注册时间"
                       width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.gmtCreate }}span>
        template>
      el-table-column>

      
      <el-table-column label="描述"
                       width="auto">
        <template slot-scope="scope">
          <span>{{ scope.row.describe }}span>
        template>
      el-table-column>

      <el-table-column align="center"
                       label=" *** 作"
                       width="150">
        <template slot-scope="scope">
          
          <router-link :to="'/editUser/' + scope.row.id">
            <el-button size="mini"
                       type="warning"
                       icon="el-icon-edit">el-button>
          router-link>
          
          <el-button style="margin-left: 10px;"
                     size="mini"
                     type="danger"
                     icon="el-icon-delete"
                     @click="deleteUser(scope.row.id)">el-button>
        template>
      el-table-column>
    el-table>

    
    <div class="block"
         style="text-align:center;margin-top:10px;">
      <el-pagination background
                     @current-change="handleCurrentChange"
                     :current-page.sync="pageParam.index"
                     :page-size="pageParam.size"
                     :total="pageParam.total"
                     layout="prev, pager, next, jumper">
      el-pagination>
    div>

  div>
template>

<script>
import user from '../api/user'

export default {
  data() {
    return {
      // 分页
      pageParam: {
        index: 1,
        size: 10,
        total: 0,
      },
      // 数据
      userList: [],
      // 一键删除
      more: false, // 删除按钮显示状态
      select: [], // 选中的数据
      // 查询参数对象
      queryParam: {
        username: '',
        nickname: '',
        phone: '',
        sex: '',
        time: '',
      },
    }
  },
  methods: {
    // 提交查询
    submitSearch() {
      // 调用下面的查询方法
      this.findUserList()
    },
    // 清空查询参数
    clearForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 每选中一个就会执行的方法
    handleSelectionChange(val) {
      if (val.length === 0) { 
        // 选中0个,隐藏按钮
        this.more = false
      } else {
        // 选中1个以上,显示一键删除按钮
        this.more = true
      }
      this.select = val
    },
    // 一键删除多个用户
    deleteMore() {
      this.$confirm('此 *** 作将删除多个用户,是否继续?', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
      }).then(() => {
        let ids = []
        // 取出用户ID
        this.select.forEach((item) => {
          ids.push(item.id)
        })
        // 调用删除多个用户的接口
        user.deleteMoreUser(ids).then((_) => {
          this.$notify({
            title: '删除成功',
            type: 'success',
          })
          this.findUserList()
        })
      })
    },
    // 切页
    handleCurrentChange(index) {
      this.pageParam.index = index
      this.findUserList()
    },
    // 查询用户列表
    findUserList() {
      user.findUserList(this.pageParam.index, this.pageParam.size, this.queryParam).then((res) => {
        this.userList = res.data.userList
        this.pageParam.total = res.data.total
      })
    },
    // 删除单个用户
    deleteUser(id) {
      this.$confirm('此 *** 作将删除改用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 调用删除接口
        user.deleteUser(id).then((_) => {
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.findUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },
  },
  created() {
    this.findUserList()
  },
}
script>
🌴 添加用户

添加 *** 作这种表单,我用的最多的就是这个组件模板

做点修改,代码如下,标签中的属性在 element ui官方都有详细的介绍,实在不懂的可以私聊我

<template>
  <div class="app">
    <div class="form">
      <el-form :model="userList" :rules="rules" ref="userList"
               label-width="100px"
               class="demo-ruleForm">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userList.username">el-input>
        el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userList.nickname">el-input>
        el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="userList.password">el-input>
        el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="userList.phone"  type="number">el-input>
        el-form-item>

        <el-form-item label="性别" prop="sex">
          
          <el-select v-model="userList.sex" placeholder="请选择性别">
            <el-option label="" value="0">el-option>
            <el-option label="" value="1">el-option>
          el-select>
        el-form-item>

        <el-form-item label="描述" prop="describe">
          <el-input type="textarea" v-model="userList.describe">el-input>
        el-form-item>
        <el-form-item>
          
          <el-button type="primary" @click="submitForm('userList')">提交el-button>
          
          <el-button @click="resetForm('userList')">重置el-button>
        el-form-item>
      el-form>
    div>
  div>
template>

<script>
export default {
  data() {
    return {
      // 用户信息表单
      userList: {
        username: '',
        nickname: '',
        password: '',
        phone: '',
        sex: '',
        describe: '',
      },
      // 校验规则,详细看 element ui 官方教程
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 调用添加用户接口
          user.addUser(this.userList).then((_) => {
            // 跳转到主页下(userList.vue)
            this.$router.push('/')
          })
        }
      })
    },
    // 清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  }
}
script>

<style>
.form {
  width: 50%;
}
/* 清除号码框的上下效果 */
.form input::-webkit-outer-spin-button,
.form input::-webkit-inner-spin-button {
	-webkit-appearance: none;
}

.form input[type='number'] {
	-moz-appearance: textfield;
}
style>

保存刷新浏览器,测试,添加用户成功

🌵 编辑用户

编辑用户和添加用户我们使用的是同一个页面,细心的伙伴可以就发现了,一个是 router 路由编辑用户的路径后面绑定了id,一个是数据列表页面的编辑按钮,外层加上了路由跳转的标签,后面携带了id参数


回到 addUser.vue 编辑,首先加上状态参数,用于页面当前状态判断

添加判断函数,判断当前页面路径是否存在参数,同时加上监听路由(如果不加,当编辑用户 *** 作时,点击左侧的添加用户,就是出现bug,感兴趣的可以去掉监听路由测试一下)

提交表单方法也要修改,判断是添加还是编辑,调用不同的接口

整体代码如下

<template>
  <div class="app">
    <div class="form">
      <el-form :model="userList" :rules="rules" ref="userList"
               label-width="100px"
               class="demo-ruleForm">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userList.username">el-input>
        el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userList.nickname">el-input>
        el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="userList.password">el-input>
        el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="userList.phone"  type="number">el-input>
        el-form-item>

        <el-form-item label="性别" prop="sex">
          
          <el-select v-model="userList.sex" placeholder="请选择性别">
            <el-option label="" value="0">el-option>
            <el-option label="" value="1">el-option>
          el-select>
        el-form-item>

        <el-form-item label="描述" prop="describe">
          <el-input type="textarea" v-model="userList.describe">el-input>
        el-form-item>
        <el-form-item>
          
          <el-button type="primary" @click="submitForm('userList')">提交el-button>
          
          <el-button @click="resetForm('userList')">重置el-button>
        el-form-item>
      el-form>
    div>
  div>
template>

<script>
import user from '../api/user'

export default {
  data() {
    return {
      // 页面状态 false->添加 *** 作,true->编辑 *** 作
      status: false,
      // 用户信息表单
      userList: {
        username: '',
        nickname: '',
        password: '',
        phone: '',
        sex: '',
        describe: '',
      },
      // 校验规则,详细看 element ui 官方教程
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.status) {
            // 调用编辑用户接口
            user.updateUser(this.userList).then(_ => {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              // 跳转到主页下(userList.vue)
              this.$router.push('/')
            })
          }else{
            // 调用添加用户接口
            user.addUser(this.userList).then((_) => {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              // 跳转到主页下(userList.vue)
              this.$router.push('/')
            })
          }
        }
      })
    },
    // 清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 判断是编辑还是添加用户
    check() {
      if(this.$route.params && this.$route.params.id) {
        // 路径存在id参数,编辑状态
        this.status = true
        user.getUserInfo(this.$route.params.id).then( res => {
          // 通过传递过来的id查询用户数据,覆盖
          this.userList = res.data.userInfo
        })
      }else {
        // 未存在id参数,添加状态
        this.status = false
      }
    }
  },
  created() {
    // 页面未显示前就先判断状态
    this.check()
  },
  watch: {
    // 监听路由变化,不然会有bug
    $route(to, from) {
      this.check()
    }
  }
}
script>

<style>
.form {
  width: 50%;
}
/* 清除号码框的上下效果 */
.form input::-webkit-outer-spin-button,
.form input::-webkit-inner-spin-button {
	-webkit-appearance: none;
}

.form input[type='number'] {
	-moz-appearance: textfield;
}
style>
🌝 全部测试





🌹 结束语

好了,整篇的教程呢到这也就结束,SpringBoot+Vue实现简单用户管理平台两篇文章也已经完稿,整篇教程即为原创一字一字手敲,也花了心思想怎么写怎么设计才能更好的直观简洁展示给大家,让大家能看懂

最后,关于教程还有什么不懂的可以评论区留言,我一定会回复的,或者有什么更好的建议和想法也可以在评论区留言,看到好的我会一一采纳,感谢大家的支持

再一次附上Gitee开源地址:https://gitee.com/yuandewei/Yuan-SpringBoot/tree/master 不用大伙翻上去复制了

都看到这里啦,点点赞呀 😋感谢阅读 😘

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1297239.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存