2020 零基础到快速开发 Vue全家桶开发电商管理系统(三)

用户列表

用户列表开发

1 通过路由的形式展示用户列表组件

//components下建 user文件夹,下建Users.vue
//index.js(router)
{   path: '/home', 
    component: Home,
    children: [ { path:'/users', component:Users }]
} 

2 在sessionStorage中保存左侧菜单的激活状态

在这里插入图片描述

//Home.vue
<el-menu :default-active="activePath" >
<el-menu-item  @click="saveNavState('/'+ subItem.path)">
data() { return { activePath:'' },   //被激活的链接地址
created() {  this.activePath = window.sessionStorage.getItem('activePath') },
methods: {
//保存链接激活状态
    saveNavState(activePath){
      window.sessionStorage.setItem('activePath',activePath)
      this.activePath = activePath
    }
}

3 绘制用户列表组件的基础布局结构

在这里插入图片描述

<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="请输入内容">
    <el-button slot="append" icon="el-icon-search"></el-button>
  </el-input>
  </el-col>
  <el-col :span="4">
  <el-button type='primary'>添加用户</el-button>
  </el-col>
 </el-row>
</el-card>
</div>
</template>
//element.js
import { Breadcrumb,BreadcrumbItem,Card,Row,Col} from 'element-ui'
Vue.use(Breadcrumb)
.....
/* global.css */  /* 因为要覆盖本来的样式,所以写在这里 */
.el-breadcrumb{
    margin-bottom: 15px;
    font-size: 12px;
}
.el-card{
    box-shadow:0 1px 1px rgba(0,0,0,0.15) !important;
}

4 获取用户列表数据

data() {
    return {
      queryInfo: { query: "", pagenum: 1, pagesize: 2 },      //获取用户列表的参数对象
      userlist: [],
      total: 0
    }
  },
created() { this.getUserList() },
  methods: {
    async getUserList() {
      const { data:res } = await this.$http.get("users", { params: this.queryInfo }) //接口文档
      if(res.meta.status!=200) return this.$message.error('获取用户列表失败')
      this.userlist=res.data.users
      this.total=res.data.total    
    }
  }

5 使用el-table组件渲染基本的用户列表

  • 为表格添加索引列
  • 自定义状态列的显示效果
  • 通过作用域插槽渲染操作列
      <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 prop="role_name" label="角色"> </el-table-column>
        <el-table-column  label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row.mg_state}} -->  <!--scope.row存的是这一行的数据  -->
            <el-switch v-model="scope.row.mg_state"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template>
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini"></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>
//element.js
import { Table,TableColumn,Switch,Tooltip} from 'element-ui'
Vue.use(Table)
.....
/* global.css */
.el-table {
    margin-top:15px;
    font-size:12px;
}

6 实现分页效果

<el-pagination
  @size-change="handleSizeChange"   
  @current-change="handleCurrentChange"
  :current-page="queryInfo.pagenum"    //当前显示第几页
  :page-sizes="[1, 2, 5, 10]"
  :page-size="queryInfo.pagesize"      //当前每页显示多少条
  layout="total, sizes, prev, pager, next, jumper"
  :total="total"    //总共多少条数据
>
</el-pagination>

methods: {
    //监听 pagesize 改变
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听页码值改变
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum=newPage
      this.getUserList()
    }

//element.js
import { Pagination} from 'element-ui'
Vue.use(Pagination)

/* global.css */
.el-pagination{
    margin-top:15px;
}

7 修改用户状态

修改后台数据
在这里插入图片描述

<el-table-column label="状态">
  <template slot-scope="scope" >
    <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"> </el-switch>
  </template>
</el-table-column>

//监听 switch 开关状态的改变
    async userStateChanged(userInfo) {
      //console.log(userInfo)
      const { data: res } = await this.$http.put( `users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state  //后台失败,但前端已经改了,需要重置回去
        return this.$message.error("更新用户状态失败!")
      }
      this.$message.success("更新用户状态成功!")
    }

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>

添加用户

添加用户

1 渲染添加用户的对话框

//User.vue
 <el-button type="primary"  @click="addDialogVisible = true">添加用户</el-button>
 <!-- 添加用户对话框 -->
    <el-dialog title="提示" :visible.sync="addDialogVisible"  width="50%" >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
data() { return { addDialogVisible: false } }

//element.js
import { Dialog } from 'element-ui'
Vue.use(Dialog)

2 渲染添加用户的表单

<!-- 内容主体区 -->
     <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></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="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
     </el-form>
     
data() {
    return {
    //添加用户的表单数据
      addForm: {
         username:"",
         password: "",
        email: "",
        mobile: ""
      },
      //表单验证规则对象
      addFormRules: {
        username: [
          { 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: "长度在 6 到 15 个字符", trigger: "blur" }
        ....
        }

3 自定义邮箱和手机号的校验

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 checkMobile = (rule,value,cb)=>{
      const regMobile= /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if(regMobile.test(value)){return cb(); }
      cb(new Error('请输入合法手机号'))
    }
    return {
     addFormRules: {
      email:[
          { required: true, message: "请输入正确邮箱地址", trigger: "blur" },
          { validator:checkEmail, trigger: 'blur' }        /*........*/
         ],
      mobile:[
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator:checkMobile, trigger: 'blur' }
        ]
        }
      }
 }

4 实现表单的重置操作

<el-dialog @close="addDialogClosed">
methods: {
 // 监听添加用户对话框关闭事件
    addDialogClosed(){ this.$refs.addFormRef.resetFields() }
}  

5 实现添加用户前的表单预校验

6 调用API完成添加用户的功能

<el-button type="primary" @click="addUser">确 定</el-button>
methods: {
   addUser() {
      this.$refs.addFormRef.validate(async valid=>{   //表单预校验
        if(!valid) return
        // 发起添加用户请求
      const {data:res} = await this.$http.post('users',this.addForm)
      if(res.meta.status!=201) { this.$message.error('添加用户失败!')  }
      this.$message.success('添加用户成功!')
      this.addDialogVisible = false
      this.getUserList()
      })
    }
  }

修改用户

修改用户

1 展示修改用户的对话框

<!-- 修改按钮 -->
    <el-button @click="showEditDialog" ></el-button>
 <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogVisible = false" >确 定</el-button>
      </span>
    </el-dialog>
 
 data() { 
      return {    
         editDialogVisible: false,//控制编辑对话框的显示与隐藏
      }
 },
 methods:{
   // 展示编辑用户的对话框
    showEditDialog() {  this.editDialogVisible =true  }  
 } 

2 根据id查询对应的用户信息并渲染修改用户的表单

<!-- 修改按钮 -->
    <el-button  @click="showEditDialog(scope.row.id)" ></el-button>
     <el-form ref="editFormRef" :model="editForm"  :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></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='mobile'>
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
    </el-form>
    
    data() { 
      return { 
        editForm: {}  // 查询到的用户信息对象
        editFormRules:{ email: [...], mobile: [....] } //编辑表单验证规则对象
      } 
    },
    methods: {
     // 展示编辑用户的对话框
     async showEditDialog(id) {
       const { data: res } = await this.$http.get('users/'+id,this.addForm)
        if (res.meta.status != 200) {
        return this.$message.error("修改用户失败!")
        }
        this.editForm = res.data    
        this.editDialogVisible = true   
    }
  }

3 实现修改用户表单的重置操作

<el-dialog @close="editDialogClosed">
methods:{ editDialogClosed() { this.$refs.editFormRef.resetFields()} }

4 完成提交修改之前的表单预验证和提交表单完成用户信息的修改

<el-button type="primary" @click="editUserInfo">确 定</el-button>
// 点击按钮,修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status != 200) {
         return this.$message.error("更新用户信息失败!")
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success("更新用户信息成功!")
      })
    }

删除用户

删除用户

1 弹窗询问是否确认删除

2 调用API完成用户的删除操作

<el-button  @click="removeUserById(scope.row.id)" ></el-button>
methods:{
  async removeUserById(id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err)
      // 如果用户确认删除,则返回值为字符串 confirm
      // 如果用户取消了删除,则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除")
      }
      const { data: res } = await this.$http.delete("users/" + id)
      if (res.meta.status != 200) {
        return this.$message.error("删除用户失败!")
      }
      this.$message.success("删除用户成功!")
      this.getUserList()
    }
  }
}

//element.js
import { MessageBox } from 'element-ui'
Vue.prototype.$confirm = MessageBox.confirm

提交到码云

(本地,云端都还没有 user 分支)

git branch   # (login)
git checkout -b user  #切换并且把改变带过去
git branch   # (user)
git status
git add .
# git status
git commit -m "完成了用户列表功能的开发"
# git status
# git branch
git push -u origin user  # 本地user分支推送到云端 origin仓库,以 user 分支进行保存 (-u 云端还没有这个分支,第一次提交)
# git branch
git checkout master
git merge user
git push
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值