egg+mysql(sequelize)+vue實現curd前端
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='收藏表';
cnpm install egg-sequelize egg-cors --save
exports.sequelize = { enable: true, package: 'egg-sequelize', }; exports.cors = { enable: true, package: 'egg-cors', };
//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配置結束
'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; }
'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;
'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.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)
<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>
<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>
<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>