2

后台

项目

egg+mysql(sequelize)+vue实现curd

项目结构

clipboard.png

mysql建表(collect)

CREATE TABLE `collect` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收藏id',
  `author` varchar(255) DEFAULT NULL COMMENT '作者',
  `date` varchar(255) DEFAULT NULL COMMENT '日期',
  `link` varchar(255) DEFAULT NULL COMMENT '链接',
  `title` varchar(255) DEFAULT NULL COMMENT '标题',
  `created_at` datetime DEFAULT NULL COMMENT '创建时间',
  `updated_at` datetime DEFAULT NULL COMMENT '更改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `title` (`title`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='收藏表';

配置

egg安装模块
cnpm install egg-sequelize egg-cors --save
config/pulgin.js
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize',
};
exports.cors = {
  enable: true,
  package: 'egg-cors',
};
config/config.default.js
 //mysql配置开始
  config.sequelize = {
    dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
    dialectOptions: {
      charset: 'utf8mb4',
    },
    database: 'egg04',
    host: 'localhost',
    port: '3306',
    username: 'root',
    password: '123456',
    timezone: '+08:00',
  };
  //mysql配置结束
  //cors配置开始
  config.security = {
    csrf: {
      enable: false,
    },
    domainWhiteList: [ 'http://localhost:8080' ],
  };
  config.cors = {
    credentials: true,
  };
    //cors配置结束

数据建模

model/collect.js
'use strict';
module.exports = app => {
    const {
        INTEGER,
        STRING,
        DATE
    } = app.Sequelize;
    const Collect = app.model.define('collect',{
        id:{
            type:INTEGER,
            primaryKey:true,
            autoIncrement:true
        },
        author:STRING,
        date:STRING,
        link:STRING,
        title:STRING,
        created_at:DATE,
        updated_at:DATE
    },{
        freezeTableName: true, //使用默认表名,不会变以collects
    })
    return Collect;
}

controller

controller/collect.js
'use strict';

const Controller = require('egg').Controller;

class CollectController extends Controller {
    async create(){
        const {ctx} = this;
        const body = ctx.request.body;
        ctx.body = await ctx.service.collect.create(body);
    }
    
    async destroy(){
        const {ctx} = this;
        const id = +ctx.params.id;
        ctx.body = await ctx.service.collect.destroy(id)
    }

    async update(){
        const {ctx} = this;
        const id = +ctx.params.id;
        const body = ctx.request.body;
        ctx.body = await ctx.service.collect.update({
            id,
            body
        })
    }

    async find() {
        const {ctx} = this;
        const id = +ctx.params.id;
        ctx.body = await ctx.service.collect.find(id)
      }

    async list(){
        const {ctx} = this;
        const query = ctx.query;
        ctx.body = await ctx.service.collect.list(query)
    }
}

module.exports = CollectController;

service

service/collect.js
'use strict';

const Service = require('egg').Service;
const{ERROR,SUCCESS} = require('../util/util')
class CollectService extends Service {
    async create(collect){
        const {ctx} = this;
        try{
            collect = await ctx.model.Collect.create(collect);
            if(!collect){
                ctx.status = 400;
                return Object.assign(ERROR,{
                    msg:`expectd collect,but got ${JSON.stringify(collect)}`
                })
            }
            ctx.status = 200;
            return Object.assign(SUCCESS,{
                data:collect
            })
        }catch(error){
            ctx.status = 500;
            throw(error)
        }
    }

    async destroy(id){
        const {ctx} = this;
        try{
            const collect = await ctx.model.Collect.findById(id);
            if(!collect){
                ctx.status = 400;
                return Object.assign(ERROR,{
                    msg:'not found collect'
                })
            }
            const res = await collect.destroy();
            ctx.status = 200;
            return Object.assign(SUCCESS,{
                data:res
            })
        }catch(error){
            ctx.status = 500;
            throw(error)
        }
    }

    async update({
        id,
        body
    }){
        const {ctx} = this;
        try{
            const collect = await ctx.model.Collect.findById(id);
            if(!collect){
                ctx.status = 400;
                return Object.assign(ERROR,{
                    msg:'not fount collect'
                })
            }
            const res = await collect.update(body);
            ctx.status = 200;
            return Object.assign(SUCCESS,{
                data:res
            })
        }catch(error){
            ctx.status = 500;
            throw(error)
        }
    }

    async find(id) {
        const {ctx} = this;
        try{
            const collect = await ctx.model.Collect.findById(id);
            if(!collect){
                ctx.status = 400;
                return Object.assign(ERROR,{
                    msg:'not found collection'
                })
            }
            ctx.status = 200;
            return Object.assign(SUCCESS,{
                data:collect
            })
        }catch(error){
            ctx.status = 500;
            throw(error)
        }
      }

    async list({
        offset = 0,
        limit = 10,
        order_by ='created_at',
        order = 'DESC'
    }){
        const {ctx} = this;
        const options = {
            offset:parseInt(offset),
            limit:parseInt(limit),
            order:[
                [order_by,order.toUpperCase()]
            ]
        }
        try{
            const res = await ctx.model.Collect.findAndCountAll(options);
            if(!res){
                ctx.status = 400;
                return Object.assign(ERROR,{
                    msg:'not fount collect'
                })
            }
            ctx.status = 200;
            return Object.assign(SUCCESS,{
                data:res
            })
        }catch(error){
            ctx.status = 500;
            throw(error)
        }
    }
}

module.exports = CollectService;

router.js

  router.post('/api/collect',controller.collect.create)
  router.delete('/api/collect/:id',controller.collect.destroy)
  router.put('/api/collect/:id',controller.collect.update)
  router.get('/api/collect',controller.collect.list)
  router.get('/api/collect/:id',controller.collect.find)

前端

查找,删除

clipboard.png

<template>
    <div class="app-collect">
        <header>
            <router-link to="/collectCreate">新建收藏</router-link>
        </header>

        <ul class="collect-main">
            <li class="main-item" v-for="item in collecData" :key="item.id">
                <a :href="item.link">{{item.title}}</a>
                <div v-if="$store.state.userInfo.username === 'admin'">
                    <router-link :to="{path:'/collectEdit',query:{id:item.id}}">编辑</router-link>
                    <button @click="deleteCollect(item.id)">删除</button>
                </div>
                
            </li>
        </ul>

    </div>
</template>

<script>
export default {
    data() {
        return {
            collecData: []
        };
    },
    methods: {
        getCollect() {
            axios
                .get("http://localhost:7001/api/collect",{
                    params:{
                        limit:2
                    }
                })
                .then(response => {
                    console.log(response);
                    this.collecData = response.data.data.rows;
                })
                .catch(error => {
                    console.log(error);
                });
        },
        deleteCollect(id){
            axios
                .delete("http://localhost:7001/api/collect/" + id)
                .then(response => {
                    console.log(response);
                    this.getCollect();
                })
                .catch(error => {
                    console.log(error);
                });
        }
    },
    created() {
        this.getCollect();
    }
};
</script>

增加

clipboard.png

<template>
    <div>
        <div>
            <label>
                <span>作者</span>
                <input type="text" v-model="author">
            </label>
        </div>
        <div>
            <label>
                <span>日期</span>
                <input type="text" v-model="date">
            </label>
        </div>
        <div>
            <label>
                <span>链接</span>
                <input type="text" v-model="link">
            </label>
        </div>
        <div>
            <label>
                <span>标题</span>
                <input type="text" v-model="title">
            </label>
        </div>
        <div>
            <button @click="createCollect">确定</button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            author: "",
            date: "",
            link: "",
            title: ""
        };
    },
    methods: {
        createCollect() {
            axios
                .post("http://localhost:7001/api/collect", {
                    author: this.author,
                    date: this.date,
                    link: this.link,
                    title: this.title
                })
                .then(response => {
                    console.log(response);
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }
};
</script>

修改

clipboard.png

<template>
    <div>
        <div>
            <label>
                <span>作者</span>
                <input type="text" v-model="author">
            </label>
        </div>
        <div>
            <label>
                <span>日期</span>
                <input type="text" v-model="date">
            </label>
        </div>
        <div>
            <label>
                <span>链接</span>
                <input type="text" v-model="link">
            </label>
        </div>
        <div>
            <label>
                <span>标题</span>
                <input type="text" v-model="title">
            </label>
        </div>
        <div>
            <button @click="editCollect">确定</button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            collectId:this.$route.query.id,
            author: "",
            date: "",
            link: "",
            title: ""
        };
    },
    methods: {
        getCollect() {
            axios
                .get("http://localhost:7001/api/collect/" + this.collectId)
                .then(response => {
                    console.log(response);
                    this.author = response.data.data.author;
                    this.date = response.data.data.date;
                    this.link = response.data.data.link;
                    this.title = response.data.data.title;
                })
                .catch(error => {
                    console.log(error);
                });
        },
        editCollect(){
            axios
                .put("http://localhost:7001/api/collect/" + this.collectId,{
                    author: this.author,
                    date: this.date,
                    link: this.link,
                    title: this.title
                })
                .then(response => {
                    console.log(response);
                    this.$router.push({path:'/'})
                })
                .catch(error => {
                    console.log(error);
                });
        }
    },
    created(){
        this.getCollect()
    }
};
</script>

渣渣辉
1.3k 声望147 粉丝

引用和评论

0 条评论