Vue2项目练手——通用后台管理项目第六节

Vue2项目练手——通用后台管理项目

  • 用户管理页
    • table表格
      • 获取表格数据
        • 目录列表
        • user.js
        • mock.js
        • index.js
        • Users.vue
      • 新增和编辑功能
        • Users.vue
      • 删除功能
        • 使用的组件
        • Users.vue

用户管理页

table表格

使用的组件和前面的表格使用的一致。

获取表格数据

目录列表

Vue2项目练手——通用后台管理项目第六节_第1张图片

user.js

import Mock from 'mockjs'

// get请求从config.url获取参数,post从config.body中获取参数
function param2Obj (url) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
        '"}'
    )
}

let List = []
const count = 200

for (let i = 0; i < count; i++) {
    List.push(
        Mock.mock({
            id: Mock.Random.guid(),
            name: Mock.Random.cname(),
            addr: Mock.mock('@county(true)'),
            'age|18-60': 1,
            birth: Mock.Random.date(),
            sex: Mock.Random.integer(0, 1)
        })
    )
}

export default {
    /**
     * 获取列表
     * 要带参数 name, page, limt; name可以不填, page,limit有默认值。
     * @param name, page, limit
     * @return {{code: number, count: number, data: *[]}}
     */
    getUserList: config => {
        const { name, page = 1, limit = 20 } = param2Obj(config.url)
        console.log('name:' + name, 'page:' + page, '分页大小limit:' + limit)
        const mockList = List.filter(user => {
            if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false
            return true
        })
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        return {
            code: 20000,
            count: mockList.length,
            list: pageList
        }
    },
    /**
     * 增加用户
     * @param name, addr, age, birth, sex
     * @return {{code: number, data: {message: string}}}
     */
    createUser: config => {
        const { name, addr, age, birth, sex } = JSON.parse(config.body)
        console.log(JSON.parse(config.body))
        List.unshift({
            id: Mock.Random.guid(),
            name: name,
            addr: addr,
            age: age,
            birth: birth,
            sex: sex
        })
        return {
            code: 20000,
            data: {
                message: '添加成功'
            }
        }
    },
    /**
     * 删除用户
     * @param id
     * @return {*}
     */
    deleteUser: config => {
        const { id } = JSON.parse(config.body)
        if (!id) {
            return {
                code: -999,
                message: '参数不正确'
            }
        } else {
            List = List.filter(u => u.id !== id)
            return {
                code: 20000,
                message: '删除成功'
            }
        }
    },
    /**
     * 批量删除
     * @param config
     * @return {{code: number, data: {message: string}}}
     */
    batchremove: config => {
        let { ids } = param2Obj(config.url)
        ids = ids.split(',')
        List = List.filter(u => !ids.includes(u.id))
        return {
            code: 20000,
            data: {
                message: '批量删除成功'
            }
        }
    },
    /**
     * 修改用户
     * @param id, name, addr, age, birth, sex
     * @return {{code: number, data: {message: string}}}
     */
    updateUser: config => {
        const { id, name, addr, age, birth, sex } = JSON.parse(config.body)
        const sex_num = parseInt(sex)
        List.some(u => {
            if (u.id === id) {
                u.name = name
                u.addr = addr
                u.age = age
                u.birth = birth
                u.sex = sex_num
                return true
            }
        })
        return {
            code: 20000,
            data: {
                message: '编辑成功'
            }
        }
    }
}

mock.js

新增代码:

import user from '@/api/mockServeData/user'

//用户列表的数据
Mock.mock('/api/user/add','post',user.createUser)
Mock.mock('/api/user/edit','post',user.updateUser)
Mock.mock('/api/user/del','post',user.deleteUser)
Mock.mock('/api/user/getUser',user.getUserList)

全部代码:

import Mock from 'mockjs'
import homeApi from "@/api/mockServeData/home";
import user from '@/api/mockServeData/user'
/*//定义请求拦截
Mock.mock('/api/home/getData',function (){
    //拦截到请求后处理的逻辑
    console.log("拦截到了")
})*/
//定义请求拦截
Mock.mock('/api/home/getData',homeApi.getStatisticalData)

//用户列表的数据
Mock.mock('/api/user/add','post',user.createUser)
Mock.mock('/api/user/edit','post',user.updateUser)
Mock.mock('/api/user/del','post',user.deleteUser)
Mock.mock('/api/user/getUser',user.getUserList)

index.js

新增代码

export const getUser=(params)=>{
    //返回用户列表  axios的get请求是在params中
    return http.get('/user/getUser',params)
}

export const addUser=(data)=>{
    //新增用户  axios的post请求是在data中
    return http.post('/user/add',data)
}

export const editUser=(data)=>{
    //编辑用户  axios的post请求是在data中
    return http.post('/user/edit',data)
}
export const delUser=(data)=>{
    //删除用户  axios的post请求是在data中
    return http.post('/user/del',data)
}

全部代码:

import http from "@/utils/request";

//请求首页数据
export const getData=()=>{
    //返回一个promise对象
    return http.get('/home/getData')
}

export const getUser=(params)=>{
    //返回用户列表  axios的get请求是在params中
    return http.get('/user/getUser',params)
}

export const addUser=(data)=>{
    //新增用户  axios的post请求是在data中
    return http.post('/user/add',data)
}

export const editUser=(data)=>{
    //编辑用户  axios的post请求是在data中
    return http.post('/user/edit',data)
}
export const delUser=(data)=>{
    //删除用户  axios的post请求是在data中
    return http.post('/user/del',data)
}

Users.vue

新增代码

 <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="name"
            label="姓名">
        el-table-column>
        <el-table-column
            prop="age"
            label="年龄">
        el-table-column>
        <el-table-column
            prop="sex"
            label="性别">
          
          <template slot-scope="scope">
            <span>{{ scope.row.sex===1?'男':'女' }}span>
          template>
        el-table-column>
        <el-table-column
            prop="birth"
            label="出生日期">
        el-table-column>
        <el-table-column
              prop="addr"
              label="地址">
        el-table-column>
        <el-table-column
          prop="action"
          label="操作">
          
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑el-button>
            <el-button size="mini" @click="handleDelete(scope.row)" type="danger">删除el-button>
          template>
        el-table-column>
      el-table>
import {getUser} from "@/api";
 methods:{
    handleEdit(row){

    },
    handleDelete(row){

    }
  },
  mounted() {
    getUser().then(({data})=>{
      console.log(data);
      this.tableData=data.list
    })
  }

全部代码:

<template>
  <div class="manage">
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">

      <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名">el-input>
        el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄">el-input>
        el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
            <el-option label="" value="1">el-option>
            <el-option label="" value="0">el-option>
          el-select>
        el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.birth" style="width: 100%;">el-date-picker>
        el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址">el-input>
        el-form-item>
      el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消el-button>
        <el-button type="primary" @click="submit">确 定el-button>
      span>
    el-dialog>
    <div class="manage-header">
      <el-button type="primary" @click="dialogVisible=true">+新增el-button>
      <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="name"
            label="姓名">
        el-table-column>
        <el-table-column
            prop="age"
            label="年龄">
        el-table-column>
        <el-table-column
            prop="sex"
            label="性别">
          
          <template slot-scope="scope">
            <span>{{ scope.row.sex===1?'男':'女' }}span>
          template>
        el-table-column>
        <el-table-column
            prop="birth"
            label="出生日期">
        el-table-column>
        <el-table-column
              prop="addr"
              label="地址">
        el-table-column>
        <el-table-column
          prop="action"
          label="操作">
          
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑el-button>
            <el-button size="mini" @click="handleDelete(scope.row)" type="danger">删除el-button>
          template>
        el-table-column>
      el-table>
    div>
  div>

template>

<script>
import {getUser} from "@/api";

export default {
  name: "Users",
  data(){
    return {
      dialogVisible:false,
      form: {
        name: '',
        age: '',
        sex: '',
        birth: '',
        addr: '',
      },
      rules: {
        name: [{required: true, message: "请输入姓名"}],
        age: [{required: true, message: "请输入年龄"}],
        sex: [{required: true, message: "请选择性别"}],
        birth: [{required: true, message: "请选择出生日期"}],
        addr: [{required: true, message: "请输入地址"}],
      },
      tableData: [],
    }
  },
  methods:{
    //提交用户表单
    submit(){
      this.$refs.form.validate((valid)=>{
        if(valid){
        //  后续对表单数据的处理
          console.log(this.form)

          //清空表单数据
          this.$refs.form.resetFields()
          //关闭弹窗
          this.dialogVisible=false
        }
      })
    },
    //弹窗关闭的时候
    handleClose(){
      //清空表单
      this.$refs.form.resetFields()
      this.dialogVisible=false
    },
    cancel(){
      this.handleClose()
    },
    handleEdit(row){

    },
    handleDelete(row){

    }
  },
  mounted() {
    getUser().then(({data})=>{
      console.log(data);
      this.tableData=data.list
    })
  }
}
script>

<style scoped>

style>

新增和编辑功能

Users.vue

新增代码:

<el-select v-model="form.sex" placeholder="请选择">
            <el-option label="" :value="1">el-option>
            <el-option label="" :value="0">el-option>
          el-select>

<el-form-item label="出生日期" prop="birth">
          <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.birth" style="width: 100%;"
              value-format="yyyy-MM-DD">
            
          el-date-picker>
        el-form-item>
 
 <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消el-button>
        <el-button type="primary" @click="submit">确 定el-button>
      span>

<el-button type="primary" @click="handleAdd">+新增el-button>
methods:{
//提交用户表单
    submit(){
      this.$refs.form.validate((valid)=>{
        if(valid){
          //  后续对表单数据的处理
          console.log(this.form)
          if(this.modalType===0){
            //新增
            addUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }else{
            //  编辑处理
            editUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }
          //清空表单数据
          this.$refs.form.resetFields()
          //关闭弹窗
          this.dialogVisible=false
        }
      })
    },
 handleEdit(row){
      console.log("row",row)
      this.modalType=1
      this.dialogVisible=true
      //注意需要对当前行数据进行深拷贝,否则会出错
      this.form=JSON.parse(JSON.stringify(row))
    },
//新增的功能
    handleAdd(){
      this.modalType=0
      this.dialogVisible=true
 }
  },
mounted() {
    this.getList()
  }

全部代码:

<template>
  <div class="manage">
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
      
      <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名">el-input>
        el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄">el-input>
        el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
            <el-option label="" :value="1">el-option>
            <el-option label="" :value="0">el-option>
          el-select>
        el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.birth" style="width: 100%;"
              value-format="yyyy-MM-DD">
            
          el-date-picker>
        el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址">el-input>
        el-form-item>
      el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消el-button>
        <el-button type="primary" @click="submit">确 定el-button>
      span>
    el-dialog>
    <div class="manage-header">
      <el-button type="primary" @click="handleAdd">+新增el-button>
      <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="name"
            label="姓名">
        el-table-column>
        <el-table-column
            prop="age"
            label="年龄">
        el-table-column>
        <el-table-column
            prop="sex"
            label="性别">
          
          <template slot-scope="scope">
            <span>{{ scope.row.sex===1?'男':'女' }}span>
          template>
        el-table-column>
        <el-table-column
            prop="birth"
            label="出生日期">
        el-table-column>
        <el-table-column
            prop="addr"
            label="地址">
        el-table-column>
        <el-table-column
            prop="action"
            label="操作">
          
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑el-button>
            <el-button size="mini" @click="handleDelete(scope.row)" type="danger">删除el-button>
          template>
        el-table-column>
      el-table>
    div>
  div>

template>

<script>
import {addUser, getUser,editUser} from "@/api";

export default {
  name: "Users",
  data(){
    return {
      dialogVisible:false,
      form: {
        name: '',
        age: '',
        sex: '',
        birth: '',
        addr: '',
      },
      rules: {
        name: [{required: true, message: "请输入姓名"}],
        age: [{required: true, message: "请输入年龄"}],
        sex: [{required: true, message: "请选择性别"}],
        birth: [{required: true, message: "请选择出生日期"}],
        addr: [{required: true, message: "请输入地址"}],
      },
      tableData: [],
      modalType:0  //0表示新增的弹窗,1表示的是编辑
    }
  },
  methods:{
    //提交用户表单
    submit(){
      this.$refs.form.validate((valid)=>{
        if(valid){
          //  后续对表单数据的处理
          console.log(this.form)
          if(this.modalType===0){
            //新增
            addUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }else{
            //  编辑处理
            editUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }
          //清空表单数据
          this.$refs.form.resetFields()
          //关闭弹窗
          this.dialogVisible=false
        }
      })
    },
    //弹窗关闭的时候
    handleClose(){
      //清空表单
      this.$refs.form.resetFields()
      this.dialogVisible=false
    },
    cancel(){
      this.handleClose()
    },
    handleEdit(row){
      console.log("row",row)
      this.modalType=1
      this.dialogVisible=true
      //注意需要对当前行数据进行深拷贝,否则会出错
      this.form=JSON.parse(JSON.stringify(row))
    },
    handleDelete(row){

    },
    //封装获取列表的数据
    getList(){
      //获取列表数据
      getUser().then(({data})=>{
        console.log(data);
        this.tableData=data.list
      })
    },
    //新增的功能
    handleAdd(){
      this.modalType=0
      this.dialogVisible=true
    }
  },
  mounted() {
    this.getList()
  }
}
script>

<style scoped>

style>

删除功能

使用的组件

Vue2项目练手——通用后台管理项目第六节_第2张图片

Users.vue

新增代码:

handleDelete(row){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser({id:row.id}).then(()=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          //  重新获取列表结果
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

全部代码:

<template>
  <div class="manage">
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
      
      <el-form ref="form" :inline="true" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名">el-input>
        el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄">el-input>
        el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
            <el-option label="" :value="1">el-option>
            <el-option label="" :value="0">el-option>
          el-select>
        el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.birth" style="width: 100%;"
              value-format="yyyy-MM-DD">
            
          el-date-picker>
        el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址">el-input>
        el-form-item>
      el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消el-button>
        <el-button type="primary" @click="submit">确 定el-button>
      span>
    el-dialog>
    <div class="manage-header">
      <el-button type="primary" @click="handleAdd">+新增el-button>
      <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="name"
            label="姓名">
        el-table-column>
        <el-table-column
            prop="age"
            label="年龄">
        el-table-column>
        <el-table-column
            prop="sex"
            label="性别">
          
          <template slot-scope="scope">
            <span>{{ scope.row.sex===1?'男':'女' }}span>
          template>
        el-table-column>
        <el-table-column
            prop="birth"
            label="出生日期">
        el-table-column>
        <el-table-column
            prop="addr"
            label="地址">
        el-table-column>
        <el-table-column
            prop="action"
            label="操作">
          
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑el-button>
            <el-button size="mini" @click="handleDelete(scope.row)" type="danger">删除el-button>
          template>
        el-table-column>
      el-table>
    div>
  div>

template>

<script>
import {addUser, getUser,editUser,delUser} from "@/api";

export default {
  name: "Users",
  data(){
    return {
      dialogVisible:false,
      form: {
        name: '',
        age: '',
        sex: '',
        birth: '',
        addr: '',
      },
      rules: {
        name: [{required: true, message: "请输入姓名"}],
        age: [{required: true, message: "请输入年龄"}],
        sex: [{required: true, message: "请选择性别"}],
        birth: [{required: true, message: "请选择出生日期"}],
        addr: [{required: true, message: "请输入地址"}],
      },
      tableData: [],
      modalType:0  //0表示新增的弹窗,1表示的是编辑
    }
  },
  methods:{
    //提交用户表单
    submit(){
      this.$refs.form.validate((valid)=>{
        if(valid){
          //  后续对表单数据的处理
          console.log(this.form)
          if(this.modalType===0){
            //新增
            addUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }else{
            //  编辑处理
            editUser(this.form).then(()=>{
              //  重新获取列表结果
              this.getList()
            })
          }
          //清空表单数据
          this.$refs.form.resetFields()
          //关闭弹窗
          this.dialogVisible=false
        }
      })
    },
    //弹窗关闭的时候
    handleClose(){
      //清空表单
      this.$refs.form.resetFields()
      this.dialogVisible=false
    },
    cancel(){
      this.handleClose()
    },
    handleEdit(row){
      console.log("row",row)
      this.modalType=1
      this.dialogVisible=true
      //注意需要对当前行数据进行深拷贝,否则会出错
      this.form=JSON.parse(JSON.stringify(row))
    },
    handleDelete(row){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser({id:row.id}).then(()=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          //  重新获取列表结果
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //封装获取列表的数据
    getList(){
      //获取列表数据
      getUser().then(({data})=>{
        console.log(data);
        this.tableData=data.list
      })
    },
    //新增的功能
    handleAdd(){
      this.modalType=0
      this.dialogVisible=true
    }
  },
  mounted() {
    this.getList()
  }
}
script>

<style scoped>

style>

Vue2项目练手——通用后台管理项目第六节_第3张图片
Vue2项目练手——通用后台管理项目第六节_第4张图片

你可能感兴趣的:(Vue基础,前端,javascript,开发语言,ecmascript)