增删改查

6 篇文章 0 订阅

前台增删改

async postHandler(){
  try{
       const {data}= await axios.post('/api/topics',this.formData)
    }catch(err){
    }
}

async removeById(id){
      if(!window.confirm()){
         return
       }
       try{
         await axios.delete(`/api/topics/${id}`)
         this.$router.push('/')
       }catch(err){
       }
 }

 async editHandler(){
   try{
        const {id,title,content}=this.formData;
        await axios.patch(`/api/topics/${id}`,{
            title,
            content
        })
        this.$router.back()
    }catch(err){
        window.alert('修改失败,请稍候重试')
    }
}

 created(){
  this.loadTopics()
},
methods:{
    async loadTopics(){
        try {
            const {data}=await axios.get('/api/topics')
            this.topics=data;
        } catch (error) {
        }
    }
}

守卫导航

// 在导航之前获取数据,可以避免看到异步渲染慢有白块的问题
  async beforeRouteEnter(to,from,next){
      const {id}=to.params
      const {data:topic}=await axios.get(`/api/topics/${id}`)
      try{
            // 有可能报错
            const {data:loginUser}=await axios.get('/api/session')
            next(vm=>{
              vm.topic=topic
              vm.isLoginUser=topic.user_id===loginUser.id
            })
        }catch(err){
            next(vm=>{
              vm.topic=topic
            })
        }
  }

分页查询

1)element-ui
<div class="block">
    <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="1"
    :page-sizes="[5, 10, 15, 20]"
    :page-size="5"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalCount">
  </el-pagination>
</div>
2)
created(){
     this.loadTopics(1,5)
 },
 methods:{
   async loadTopics(page,pageSize){
       try {
         const {data}=await axios.get(`/api/topics?_page=${page}&_limit=${pageSize}`)
         this.topics=data.topics;
         this.totalCount=data.count
       } catch (error) {

       }
   },
    handleSizeChange(val) {
     this.loadTopics(1,val)
   },
   handleCurrentChange(val) {
     this.loadTopics(val,5)
   }
 }

后台增删改查

/**
 * 创建话题
 * @param {*} req 
 * @param {*} res 
 */
exports.create=async (req,res,next)=>{
    try{

        // 获取表单数据
        const body=req.body
        body.user_id=req.session.user.id
        body.create_time=moment().format('YYYY-MM-DD hh:mm:ss')
        body.modify_time=moment().format('YYYY-MM-DD hh:mm:ss')

        const sqlStr=`
            INSERT INTO topics(title,content,user_id,create_time,modify_time) 
            VALUES ('${body.title}','${body.content}','${body.user_id}','${body.create_time}','${body.modify_time}')
        `
        const ret=await db.query(sqlStr)
        const [topic]=await db.query(`SELECT * FROM topics WHERE id='${ret.insertId}'`)
        res.status(201).json(topic)
    }catch(err){
        next(err)
    }
}

/**
 * 删除话题
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
exports.destroy=async (req,res,next)=>{
    // 1.判断是否登录
    // 2.判断当前话题是否属于当前登录用户
    // url中 :id叫动态路由参数,可以通过url.params获取
    // 查询字符串:req.query
    // post:req.body
    // 动态路径参数:req.params
    try{

        const {id} =req.params
        // 执行删除操作
        await db.query(`DELETE FROM topics where id=${id}`)
        res.status(201).json({})
    }catch(err){
        next(err)
    }
}

/**
 * 更新话题
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
exports.update=async (req,res,next)=>{
    try{
        const {id} =req.params
        const body=req.body
        const sqlStr=`
            UPDATE topics SET title='${body.title}',content='${body.content}',modify_time='${moment().format('YYYY-MM-DD hh:mm:ss')}'
            WHERE id=${id}
        `
        await db.query(sqlStr)
        const [updateTopic]=await db.query(`SELECT * FROM topics WHERE id=${id}`)
        res.status(201).json(updateTopic)
    }catch(err){
        next(err)
    }
}

exports.get=async (req,res,next)=>{
    try{
        const {id}=req.params
        const sqlStr=`
            SELECT * FROM topics WHERE id=${id}
        `
        const ret=await db.query(sqlStr)
        res.status(200).json(ret[0])
    }catch(err){
        next(err)
    }
}

分页

/**
 * 话题查询
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
exports.list=async (req,res,next)=>{

    try{
         // _page第几页 _limit每页多少条
        const {_page=1,_limit=20}=req.query
        if(_page<1){
            _page=1
        }
        if(_limit<1){
            _limit=1
        }
        if(_limit>20){
            _limit=20
        }
        // 页数 从第几条开始 每页条数
        // 1      0          20
        // 2      20         20
        // 3      40         20
        // _page (_page-1)*_limit   _limit
        const sqlStr=`
            SELECT * FROM topics limit ${(_page-1)*_limit},${_limit}
        `
        const topics=await db.query(sqlStr)
        const [{count}]=await db.query(`SELECT COUNT(1) as count FROM topics`)
        res.status(200).json({topics,count})
    }catch(err){
        next(err)
    }
}

查询条件拼接

exports.andCondition=(query)=>{
let str=’ 1=1 ’
for(let key in query){
str+=and ${key}='${query[key]}'
}
return str
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值