vue+mysql+egg.js 搭建后台服务(零基础 增删改查)

话不多说,先上图

目录

一、后台

二、前端(vuecli3 脚手架   iview ui)


一、后台

egg.js 中文官网

我这里用的是egg.js 脚手架搭建的

首先打开你要放的文件夹的位置,然后点击上面的路径cmd

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
$ npm run dev
$ open http://localhost:7001

目录结构是这样的

首先我们用的是mysql  

$ npm i --save egg-mysql

package.json 

 // config/plugin.js

'use strict';
exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

 // config/config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1612249951097_2119';

  // add your middleware config here
  config.middleware = [];

  // 配置与Mysql数据库的连接
  config.mysql = {
    // 数据库信息配置
    client: {
      // host
      host: 'localhost',
      // 端口号
      port: '3306',
      // 用户名
      user: 'root',
      // 密码
      password: '123456',
      // 数据库名
      database: 'localmysql',
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: true,
  }


  // add your user config here
  const userConfig = {
    myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
};

app/router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/getUserList', app.controller.user.getUserList);//获取用户类表
  router.get('/getUserDetail', app.controller.user.getUserDetail);//获取用户详情
  router.post('/creatOrUpdata', app.controller.user.creatOrUpdata);//新建或者更新用户信息
  router.delete('/deleteUserById', app.controller.user.deleteUserById);//删除
};

 app/controller/user.js

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
    // 获取用户列表
    async getUserList() {
        const { ctx } = this;
        const result = await ctx.service.user.getUserList();
        ctx.body = result;
    }
    // 获取用户详情
    async getUserDetail() {
        const { ctx } = this;
        const result = await ctx.service.user.getUserDetail();
        ctx.body = result;
    }
    // 新建或者更新用户
    async creatOrUpdata() {
        const { ctx } = this;
        const result = await ctx.service.user.creatOrUpdata();
        ctx.body = result;
    }
    // 删除用户
    async deleteUserById() {
        const { ctx } = this;
        const result = await ctx.service.user.deleteUserById();
        ctx.body = result;
    }
}
module.exports = UserController;

 app/service/user.js

// app/service/user.js
const Service = require('egg').Service;
class UserService extends Service {
    // 获取列表
    async getUserList() {
        let { app } = this;
        let result = await app.mysql.query('select * from user');
        return {
            data: result,
        };
    }
    // 获取详情
    async getUserDetail() {
        let param = this.ctx.query
        let { app } = this;
        let result = await app.mysql.query('select * from user where id=?', param.id);
        return {
            data: result,
        };
    }
    // 新建或者编辑
    async creatOrUpdata() {
        let param = this.ctx.request.body
        let { app } = this;
        let result
        if (this.ctx.request.body.id) {
            if (app.mysql.query('select * from user where id=?', param.id)) {
                result = await app.mysql.update('user', param)  // 参数1:表名  参数2:数据
            } else {
                result = await app.mysql.insert('user', param)  // 参数1:表名  参数2:数据
            }
        } else {
            result = await app.mysql.insert('user', param)  // 参数1:表名  参数2:数据
        }
        return {
            data: result,
        };
    }
    // 删除用户
    async deleteUserById() {
        let param = this.ctx.query
        let { app } = this;
        let result = await app.mysql.delete('user', param)
        return {
            data: result,
        };
    }
}
module.exports = UserService;

问题:在我npm run dev 运行的时候我发现会报错,查了一下发现是因为数据库原因。解决连接:https://www.cnblogs.com/taohuaya/p/11401109.html

再次运行 http://127.0.0.1:7001/user 就有返回值了

因为Web 安全概念所以post请求中要传csrf 防范

官方文档:https://eggjs.org/zh-cn/core/security.html

解决连接:https://blog.csdn.net/qq_36763293/article/details/95061913

这里我们不做安全就是说访问不需要安全验证的下载依赖  npm i egg-security

在 config/config.default.js 

config.security = {
    xframe: {
      enable: false,
    },
    csrf: {
      enable: false,
    },
  };

然后就不设置安全了

二、前端(vuecli3 脚手架   iview ui)

  1. <template>
      <div class="home">
        <Button type="primary" @click="open">新建</Button>
        <Table
          width="550"
          border
          :columns="columns2"
          :data="data3"
          @on-ok="creatOrUpdata"
          @on-cancel="cancel"
        ></Table>
        <Modal v-model="modal1" title="详情">
          <Form ref="userForm" :model="userForm">
            <FormItem prop="user">
              <Input type="text" v-model="userForm.username" placeholder="Username">
                <Icon type="ios-person-outline" slot="prepend"></Icon>
              </Input>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="error" size="large" @click="creatOrUpdata">确定</Button>
          </div>
        </Modal>
      </div>
    </template>
    
    <script>
    export default {
      name: "Home",
      components: {
        // HelloWorld
      },
      data() {
        return {
          columns2: [
            {
              title: "id",
              key: "id",
              fixed: "left",
            },
            {
              title: "名称",
              key: "username",
            },
            {
              title: "Action",
              key: "action",
              fixed: "right",
              width: 130,
              render: (h, params) => {
                return h("div", [
                  h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small",
                      },
                      on: {
                        click: () => {
                          this.deleteUserById(params);
                        },
                      },
                    },
                    "删除"
                  ),
                  h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small",
                      },
                      on: {
                        click: () => {
                          this.getUserDetail(params);
                        },
                      },
                    },
                    "编辑"
                  ),
                ]);
              },
            },
          ],
          data3: [],
          modal1: false,
          userForm: {
            id: null,
            username: null,
          },
        };
      },
      methods: {
        getUserList() {
          this.http.get("/api/getUserList").then((res) => {
            this.data3 = res.data.data;
          });
        },
        getUserDetail(data) {
          this.modal1 = true;
          let param = {
            id: data.row.id,
          };
          this.http.get("/api/getUserDetail", param).then((res) => {
            this.userForm = res.data.data[0];
          });
        },
        creatOrUpdata() {
          if (!this.userForm.id) {
            delete this.userForm.id;
          }
          let param = this.userForm;
          console.log(param, "param");
          this.http.post("/api/creatOrUpdata", param).then((res) => {
            this.modal1 = false;
            this.getUserList();
          });
        },
        deleteUserById(data) {
          let param = {
            id: data.row.id,
          };
          this.http.delete("/api/deleteUserById", param).then((res) => {
            this.getUserList();
          });
        },
        open() {
          this.modal1 = true;
          this.userForm.id = "";
          this.userForm.username = "";
        },
        cancel() {
          this.modal1 = false;
        },
      },
      mounted() {
        this.getUserList();
      },
    };
    </script>
    

三、数据库(id自增)

 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
SpringBoot是一款以简化开发的方式来构建Java应用程序的框架,它提供了许多开箱即用的特性和便捷的配置方式。Thymeleaf是一个用于处理服务器端渲染的模板引擎,可以将动态数据注入到HTML模板中。SSM是指Spring+SpringMVC+MyBatis的组合,是一套经典的Java Web开发框架。Vue.js是一款用于构建用户界面的渐进式框架,可以实现前端的组件化开发和数据驱动视图更新。 要实现简单的增删改查功能,可以按照以下步骤进行: 1. 首先,使用SpringBoot创建一个新的项目,并引入Thymeleaf、SSM和Vue.js相关的依赖。 2. 创建一个数据库表,用于存储需要进行增删改查操作的数据。可以使用MySQL等关系型数据库。 3. 在SpringBoot的配置文件中配置数据库连接信息,并创建对应的数据源和事务管理器。 4. 创建实体类,在实体类中定义需要操作的属性和对应的数据字段。 5. 创建MyBatis的Mapper接口和对应的XML文件,用于定义数据库操作的SQL语句。 6. 在SpringBoot的配置类中配置MyBatis相关的扫描和注入。 7. 创建控制器类,处理前端请求。 8. 在控制器类中定义增删改查的方法,并调用对应的Mapper接口执行数据库操作。 9. 创建前端页面,使用Vue.js来实现数据的展示和交互。 10. 在前端页面中绑定相应的事件和请求,通过HTTP请求调用后端控制器的方法。 11. 在页面中显示查询的数据,并提供相应的操作按钮,通过绑定事件来实现增删改的功能。 12. 启动项目,通过浏览器访问前端页面,即可进行增删改查的操作。 以上是一个基本的步骤,具体的实现会涉及到很多细节,需要根据具体的需求和技术选型来进行调整和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

侧耳倾听...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值