6.8【微信小程序全栈开发课程】清空所有记录

在个人中心页面有一个清空记录的功能,点击清空记录,会提示是否确认清空记录提示框。用户点击确认后,删除该用户所有的历史record记录数据

1、添加方法

(1)引用post等工具函数
//参考代码,无需粘贴
//<script>


  //需要添加的部分
  import {post,showModal,showSuccess} from '@/util'
(2)编辑me.vue文件,在methods函数中添加deleteRecords方法,用来请求后台清空记录
//参考代码,无需粘贴
//showOpinion () {
  //...
//},


//需要添加的部分
async deleteRecords () {
  try{
    const res = await post('/weapp/deleterecords', {openid:this.userinfo.openId})
    console.log("从后端返回的执行正确的信息是:",res)
    showSuccess("记录已清空~")
  }catch(e){
    showModal('清空失败', "请重试哦~")
    console.log("从后端返回的执行错误的信息是:",e)
  },
}
(3)添加提示框方法

点击清零按钮,出现提示框,提示是否确认清空记录

确认清零执行deleteRecords方法

取消清零不执行任何方法

//参考代码,无需粘贴
//async deleteRecords () {
  //...
//},


//需要添加的部分
deleteConfirm () {
  var that = this
  //用户点击确认后,调用上面添加的deleteRecords方法
  wx.showModal({
    content: `清空之后不能恢复哦~确定要清空吗?`,
    success: function (res) {
      if (res.confirm) {
        that.deleteRecords()
      }
    }
  })
},

2、在后端添加路由

(1)创建操作文件deleterecords.js

先在后端server/controllers文件夹中创建操作文件deleterecords.js

在操作文件中实现:查询该用户所有record记录,并删除

(2)添加路由

在路由管理文件server/routes/index.js文件中添加路由

//需要添加的代码
router.post('/deleterecords', controllers.deleterecords)


//参考代码,无需粘贴
//module.exports = router

3、编辑后端操作文件

也就是server/controllers/deleterecords.js文件,查询该用户所有record记录并删除

const {mysql} = require('../qcloud')

module.exports = async (ctx) => {
  const {openid} = ctx.request.body
  try{
    const res = await mysql('records')
        .where("openid",openid).del()
    // 执行成功返回的数据
    ctx.state.data = {
      code: 0,
      msg: 'success'
    }
    console.log("执行成功")
  }catch(e){
    console.log("执行错误:",e)
    // 执行失败返回的数据
    ctx.state = {
      code: -1,
      data: {
        msg: '清除失败' + e.sqlMessage
      }
    }
  }
}

4、添加点击事件

编辑me.vue文件夹template部分,将deleteConfirm方法添加到页面的点击事件上

<!-- 在这一行上面添加点击事件 -->
<div class="row" @click='deleteConfirm'>


<!-- 参考代码,无需粘贴
  <label class="left">
    <img class="img" src="/static/images/delete.png">
  </label>
  <label class="name">&nbsp;&nbsp;清空记录</label>
  ...
</div> -->

5、添加分享函数

分享函数是onShareAppMessage,与onShow函数是同级函数,需要注意不要写在methods函数里面

//参考代码,无需粘贴
//onShow () {
  //...
//},


//需要添加的代码
onShareAppMessage(e) {
  return {
    title: "真自律",
    path: "/pages/index/main",
    imageUrl: ""
  }
}

6、测试

在「我的」页面,点击清空记录这一栏,出现提示框,点击确定后,记录页面已经没有任何记录了
image.png

作者:猫宁一
全栈程序媛₍ᐢ •⌄• ᐢ₎一枚~ 热爱学习!热爱编程!
可关注【猫宁一】公众号领取我所有全栈项目代码哦~

点击查看课程目录:微信小程序全栈开发课程目录

发布了131 篇原创文章 · 获赞 136 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/shine_a/article/details/102611599
今日推荐