zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue+element ui+腾讯云开发打造会员管理系统之实战教程(四)用户管理

2023-09-14 09:13:53 时间

功能概述

为了方便商家日常管理自己的顾客信息,设计了此模块,可以新增用户,记录顾客的基本信息,如姓名、年龄、性别、联系电话和送货地址,如果顾客需要开通会员的,可以在此模块进行开卡操作,开卡之后自动记录开卡的时间并将用户的身份改为会员。

列表功能

在这里插入图片描述

  • 输入姓名和电话可以过滤用户信息
  • 点击新增可以录入用户基本信息
  • 在操作栏有编辑、删除、开卡三个操作
  • 点击导出可以将本页的用户信息导出为excel
  • 点击下边的分页可以切换数据,也可以下拉选择每页的显示条数

新增页面

在这里插入图片描述

  • 姓名、电话为必录项
  • 年龄只允许输入数字
  • 电话需要验证是否是正确的手机号码
  • 性别为下拉框,值为男、女、其他

其他操作

  • 修改

    修改页面需要带入上一次操作的信息,在此基础上进行修改

  • 删除
    直接删除数据

  • 开卡
    点击开卡后需要记录开卡时间,并将用户的状态置为会员状态

路由注册

在基础路由注册用户管理配置

{
    path: '/user',
    component: Layout,
    children: [{
      path: 'index',
      name: 'user',
      component: () => import('@/views/user/index'),
      meta: { title: '用户管理', icon: 'user' }
    }]
  }

页面配置

在views文件夹下新增用户页面
在这里插入图片描述

业务代码

<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="姓名" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.telphone" placeholder="电话" style="width: 200px;margin-left:10px;margin-right:10px" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column v-if="show" label="ID" prop="_id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="电话" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.telphone }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="联系地址" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="290" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status==0" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status==0" icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button v-if="row.status==0" icon="el-icon-s-finance" size="mini" type="success" @click="handleOpen(row,$index)">
            开卡
          </el-button>
          <el-button v-if="row.status==1" icon="el-icon-view" size="mini" type="success" @click="handleView(row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 500px; margin-left:50px;">
        <el-form-item v-if="show" label="ID" prop="_id">
          <el-input v-model="temp._id" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="temp.sex" class="filter-item" placeholder="请选择">
            <el-option v-for="item in options" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="temp.age" />
        </el-form-item>
        <el-form-item label="电话" prop="telphone" required>
          <el-input v-model="temp.telphone" />
        </el-form-item>
        <el-form-item label="送货地址">
          <el-input v-model="temp.address" :autosize="{ minRows: 2, maxRows: 10}" type="textarea" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogAddFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 500px; margin-left:50px;">
        <el-form-item v-if="show" label="ID" prop="_id">
          <el-input v-model="temp._id" />
        </el-form-item>
        <el-form-item label="姓名">
          {{ temp.name }}
        </el-form-item>
        <el-form-item label="电话">
          {{ temp.telphone }}
        </el-form-item>
        <el-form-item label="开卡日期">
          {{ temp.registerdate }}
        </el-form-item>
        <el-form-item label="余额">
          {{ temp.balance }}
        </el-form-item>
        <el-form-item label="充值金额">
          <el-input v-model.number="temp.addmoney" prop="addmoney" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="addMoney()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="用户查看">
      <el-row>
        <el-col :span="12"><div class="grid-content">姓名:{{ temp.name }}</div></el-col>
        <el-col :span="12"><div class="grid-content">性别:{{ temp.sex }}</div></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"><div class="grid-content">年龄:{{ temp.age }}</div></el-col>
        <el-col :span="12"><div class="grid-content">电话:{{ temp.telphone }}</div></el-col>
      </el-row>
      <el-row>
        <el-col :span="24"><div class="grid-content">地址:{{ temp.address }}</div></el-col>
      </el-row>
      <el-row>
        <el-col :span="12"><div class="grid-content">余额:{{ temp.balance }}</div></el-col>
        <el-col :span="12"><div class="grid-content">开卡日期:{{ temp.registerdate }}</div></el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { getList } from '@/api/customer'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  components: { Pagination },
  directives: { waves },
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
      // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
      // 所以我就在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      list: null,
      listLoading: true,
      show: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        telphone: undefined
      },
      options: ['男', '女', '其他'],
      statusOptions: ['published', 'draft', 'deleted'],
      temp: {
        _id: undefined,
        name: '',
        sex: '',
        age: '',
        telphone: '',
        address: '',
        status: 0
      },
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户',
        add: '充值'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '姓名是必录项', trigger: 'blur' }],
        telphone: [{ validator: checkPhone, trigger: 'blur' }],
        age: [{ type: 'number', message: '年龄必须为数字', trgger: 'blur' }],
        addmoney: [{ required: true, type: 'number', message: '金额必须为数字', trgger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      downloadLoading: false
    }
  },
  async created() {
    // const username = this.$store.state.user.username
    // const password = this.$store.state.user.password
    const loginState = this.$cloudbase.auth().hasLoginState()

    if (loginState) {
      // 登录态有效
      this.fetchData()
    } else {
      // 没有登录态,或者登录态已经失效
      await this.$store.dispatch('user/logout')
      this.$cloudbase.auth({ persistence: 'local' }).signOut()
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
    // this.$cloudbase.auth({ persistence: 'local' }).signInWithEmailAndPassword(username, password)
  },
  methods: {
    async fetchData() {
      this.listLoading = true
      const queryString = { status: 0 }
      if (this.listQuery.name) {
        queryString.name = this.listQuery.name
      }
      if (this.listQuery.telphone) {
        queryString.telphone = this.listQuery.telphone
      }
      const queryResult = await this.$cloudbase.database().collection('customer').where(queryString).skip((this.listQuery.page - 1) * this.listQuery.limit).limit(this.listQuery.limit).orderBy('createdate', 'desc').get()
      const queryTotal = await this.$cloudbase.database().collection('customer').where(queryString).count()
      this.list = queryResult.data
      this.listLoading = false
      this.total = queryTotal.total
      /* getList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })*/
    },
    resetTemp() {
      this.temp = {
        _id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$cloudbase.database().collection('customer').add({
            name: this.temp.name,
            sex: this.temp.sex,
            age: this.temp.age,
            telphone: this.temp.telphone,
            address: this.temp.address,
            createdate: new Date(),
            status: 0
          }).then((res) => {
            this.temp._id = res.id
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          }).catch((e) => {})
        }
      })
    },
    handleFilter() {
      this.fetchData()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['姓名', '性别', '年龄', '电话', '联系地址']
        const filterVal = ['name', 'sex', 'age', 'telphone', 'address']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          this.$cloudbase.database().collection('customer').doc(this.temp._id)
            .update({
              name: this.temp.name,
              sex: this.temp.sex,
              age: this.temp.age,
              telphone: this.temp.telphone,
              address: this.temp.address,
              status: 0
            }).then(res => {
              const index = this.list.findIndex(v => v._id === this.temp._id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '操作提示',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async handleDelete(row, index) {
      await this.$cloudbase.database().collection('customer').doc(row._id).remove()
      this.$notify({
        title: '操作提示',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.fetchData()
    },
    async handleOpen(row, index) {
      await this.$cloudbase.database().collection('customer').doc(row._id).update({
        balance: 0,
        status: 1,
        registerdate: new Date()
      })
      this.$notify({
        title: '操作提示',
        message: '开卡成功',
        type: 'success',
        duration: 2000
      })
      this.fetchData()
    },
    handleView(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.registerdate = parseTime(this.temp.registerdate, '{y}-{m}-{d}')
      this.pvData = this.temp.items
      this.dialogPvVisible = true
    },
    handleAdd(row) {
      this.temp = Object.assign({}, row)
      this.temp.registerdate = parseTime(this.temp.registerdate, '{y}-{m}-{d}')
      this.dialogAddFormVisible = true
    }

  }
}
</script>
<style scoped>
.filter-container{
  padding-bottom:10px
}
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
  .el-row {
    margin-bottom: 5px;
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    font-size:16px;
    text-align: left;
    vertical-align: bottom;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .el-header, .el-footer {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 200px;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    line-height: 160px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
</style>

开发流程

因为一旦涉及到业务模块开发就先需要先看明白需求文档要求的功能,然后结合前后端的技术来进行拆分。需求比较明确一共分为表格、弹出框、异步的操作

表格组件

这个时候就需要我们打开element的技术文档寻找组件
element
将写代码解释为搬砖我觉得还是挺贴切的,作为码农,我们先需要看一下给的图纸,然后寻找合适的砖,砖为标准的砖,我们为了符合图纸的需要需要进行一定的裁剪和调整
找到我们需要的表格组件
在这里插入图片描述
砖选好了之后就是程序员最重要的操作,复制粘贴,大胆的ctrl+C和ctrl+v吧,搬砖的动作一定要快

<el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column v-if="show" label="ID" prop="_id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="电话" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.telphone }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="联系地址" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="290" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status==0" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status==0" icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button v-if="row.status==0" icon="el-icon-s-finance" size="mini" type="success" @click="handleOpen(row,$index)">
            开卡
          </el-button>
          <el-button v-if="row.status==1" icon="el-icon-view" size="mini" type="success" @click="handleView(row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

一般高级码农在给你设计标准砖的时候已经考虑到你粘贴后需要改的地方,基本上就是两类操作,一种是外观的切割,他给你抽象出很多的属性来,一种是这个砖可以有哪些操作,他允许你可以定义哪些方法,专业一点叫支持的事件,比如你点他一下子,砰,弹出个框框来这叫点击事件,具体我们怎么看呢,他的说明书也比较明白
在这里插入图片描述
这一栏是说外观能做哪些改变
在这里插入图片描述
这一栏是说可以做哪些操作,还是比较明了的

分页组件

有了表格之后数据量比较多的时候我们还需要分页,再去砖头里刨一下,这块不错
在这里插入图片描述
我们再改造一下子

<pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

弹出框

我们点击新增的时候需要新增的页面,在传统开发这个时候你需要新写一个页面,然后打开窗口显示,我们这次这个技术选型叫单页面应用,所有的操作都是在一个窗口完成的,还是会高级一点点的,再去砖头堆里刨一下这个比较符合
在这里插入图片描述
改造一下子

<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 500px; margin-left:50px;">
        <el-form-item v-if="show" label="ID" prop="_id">
          <el-input v-model="temp._id" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="temp.sex" class="filter-item" placeholder="请选择">
            <el-option v-for="item in options" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="temp.age" />
        </el-form-item>
        <el-form-item label="电话" prop="telphone" required>
          <el-input v-model="temp.telphone" />
        </el-form-item>
        <el-form-item label="送货地址">
          <el-input v-model="temp.address" :autosize="{ minRows: 2, maxRows: 10}" type="textarea" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

vue的基本结构

码代码基本都是有模板的,不同的功能放在不同的位置就会有不同的效果,vue基本是分为三块,template、script、style,template放页面的各种组件,script放各种业务的处理逻辑,style主要放样式,刚才我们是主要在template里操作,下边高级一点在script里操作
如果需要用到其他组件的在使用之前需要导入

import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

引入之后使用需要放到components里

 components: { Pagination }

相较传统开发,我们如果前端页面需要使用数据都是在后端写入到request对象中,vue需要先定义数据结构,数据结构定义到data对象里,需要用到啥就定义啥,比如表格组件需要一个list对象那么我们就定义个list对象

data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
      // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
      // 所以我就在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      list: null,
      listLoading: true,
      show: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        telphone: undefined
      },
      options: ['男', '女', '其他'],
      statusOptions: ['published', 'draft', 'deleted'],
      temp: {
        _id: undefined,
        name: '',
        sex: '',
        age: '',
        telphone: '',
        address: '',
        status: 0
      },
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户',
        add: '充值'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '姓名是必录项', trigger: 'blur' }],
        telphone: [{ validator: checkPhone, trigger: 'blur' }],
        age: [{ type: 'number', message: '年龄必须为数字', trgger: 'blur' }],
        addmoney: [{ required: true, type: 'number', message: '金额必须为数字', trgger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      downloadLoading: false
    }
  }

在传统开发里一般我们页面加载的时候需要初始化一下数据,比如触发一下表格的加载事件,vue里它叫生命周期函数,我们这里定义一下组件创建时候执行一下表格数据加载,在实际操作的时候发现页面一刷新腾讯的登录状态就没有了所以做了一下身份的判断,有登录信息则加载数据,没有就直接返回登录页

async created() {
    // const username = this.$store.state.user.username
    // const password = this.$store.state.user.password
    const loginState = this.$cloudbase.auth().hasLoginState()

    if (loginState) {
      // 登录态有效
      this.fetchData()
    } else {
      // 没有登录态,或者登录态已经失效
      await this.$store.dispatch('user/logout')
      this.$cloudbase.auth({ persistence: 'local' }).signOut()
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
    // this.$cloudbase.auth({ persistence: 'local' }).signInWithEmailAndPassword(username, password)
  }

这些都完事之后就是具体的业务逻辑的编写了

加载列表数据

async fetchData() {
      this.listLoading = true
      const queryString = { status: 0 }
      if (this.listQuery.name) {
        queryString.name = this.listQuery.name
      }
      if (this.listQuery.telphone) {
        queryString.telphone = this.listQuery.telphone
      }
      const queryResult = await this.$cloudbase.database().collection('customer').where(queryString).skip((this.listQuery.page - 1) * this.listQuery.limit).limit(this.listQuery.limit).orderBy('createdate', 'desc').get()
      const queryTotal = await this.$cloudbase.database().collection('customer').where(queryString).count()
      this.list = queryResult.data
      this.listLoading = false
      this.total = queryTotal.total
      /* getList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })*/
    }

初学的同学可能不明白方法之前为啥要加一个async关键字,其实就是为了和await搭配使用,就像CP一样在一起才能擦出爱情的小火花,其实就是不让函数异步调用要等待它返回结果后继续向下执行
有某位同事说软件有啥难的无非就是增删改查么,道理倒是也不差,那我们是如何查询数据的呢,这就涉及到后端开发了,我们这一次的选型是腾讯的云开发,它搭配的是mongodb,叫非结构化数据库,特点是你不用事先创建表、创建字段,过程中有需要更改的也可以随时调整还是比较方便的
具体的操作步骤是先登录腾讯的云开发,选择你开通的按量付费的资源,然后点击数据库
在这里插入图片描述
新建集合,其实就是建表的意思,我们加一个customer的集合
然后就是继续搬砖的过程,只不过我们这次是看腾讯云的API
腾讯云
在这里插入图片描述
调用分为几步,一个是获得数据库的引用,之后获取集合,然后就是获取数据了

async fetchData() {
      this.listLoading = true
      const queryString = { status: 0 }
      if (this.listQuery.name) {
        queryString.name = this.listQuery.name
      }
      if (this.listQuery.telphone) {
        queryString.telphone = this.listQuery.telphone
      }
      const queryResult = await this.$cloudbase.database().collection('customer').where(queryString).skip((this.listQuery.page - 1) * this.listQuery.limit).limit(this.listQuery.limit).orderBy('createdate', 'desc').get()
      const queryTotal = await this.$cloudbase.database().collection('customer').where(queryString).count()
      this.list = queryResult.data
      this.listLoading = false
      this.total = queryTotal.total
      /* getList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })*/
    }

新增数据

handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    }

新增数据分为两步操作,一步是把隐藏的窗口显示出来,其实有时候我们看到的大多数都是假象,假的久了也就变真了,第二步就是将数据保存到数据库中

createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$cloudbase.database().collection('customer').add({
            name: this.temp.name,
            sex: this.temp.sex,
            age: this.temp.age,
            telphone: this.temp.telphone,
            address: this.temp.address,
            createdate: new Date(),
            status: 0
          }).then((res) => {
            this.temp._id = res.id
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          }).catch((e) => {})
        }
      })
    }

数据提交进来表格就多了一条数据,是不是很简单呢

源码

源码请访问
https://gitee.com/tuodagitee/membercms.git