Vue2+axios+Express+MySQL实现前后端交互

导读:本篇文章讲解 Vue2+axios+Express+MySQL实现前后端交互,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、后台

         1. 确定MySQL的表格:明确数据库 (mvc) —- 数据表(ssm_book)

         2. 创建Express项目:mysql2、cors、Sequelize(ORM)、nodemon

         3. dao层(model、连接数据库、crud操作)

         4. service层(调用dao层)

         5. 接口层(接口地址与service层的方法的映射)

         6. 接口测试

二、前端

         1. 创建vue2项目

         2. 安装axios库

         3. 创建组件:与后台进行交互实现增、删、查

三、示例代码

         后台:

//dao/model/BookModel.js

const Sequelize = require('sequelize')
const MysqlInstance = require('../config/mysqlconfig')

const BookModel = MysqlInstance.define('ssm_book',{
    bookId: {
        type: Sequelize.DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        field:'book_id'
    },
    bookName: {
        type: Sequelize.DataTypes.STRING(100),
        allowNull: false,
        field: 'book_name'
    },
    bookAuthor: {
        type: Sequelize.DataTypes.STRING(50),
        allowNull: false,
        field: 'book_author'
    },
    bookDate: {
        type: Sequelize.DataTypes.DATE,
        allowNull:false,
        field:'book_date'
    },
    bookPrice: {
        type: Sequelize.DataTypes.DECIMAL(10,2),
        allowNull:false,
        field: 'book_price'
    }
},{
    freezeTableName: true,
    timestamps: false
})

module.exports = BookModel
//dao/crud/BookDao.js

// const Op = require('sequelize').Op
const BookModel = require('../model/BookModel')

// 增加图书
exports.insertBook = async function (book){
    return await BookModel.create({
        bookName: book.bookName,
        bookAuthor:book.bookAuthor,
        bookDate: book.bookDate,
        bookPrice: book.bookPrice
    })
}

// 删除图书:按id删除
exports.removeBook = async function(id){
    return  await BookModel.destroy({
        where: {
            bookId:id
        }
    })
}

// 查询所有
exports.queryAllBook = async function(){
    return await BookModel.findAll()
}
//dao/config/mysqlconfig.js

const Sequelize = require('sequelize')

const MySQLInstance = new Sequelize('mvc','root','123456',{
    host:'localhost',
    port: 3306,
    dialect: 'mysql',
    pool:{
        max: 20,
        min: 3,
        idle: 2000
    },
    define: {
        charset: 'utf8'
    }
})

module.exports = MySQLInstance;
//service/BookService.js

const BookDao = require('../dao/crud/BookDao')

// 增加图书
exports.addBook = function (req,res){
    let book = {
        bookName: req.body.bookName,
        bookAuthor: req.body.bookAuthor,
        bookDate: req.body.bookDate,
        bookPrice: req.body.bookPrice
    }
    BookDao.insertBook(book).then(result=>{
        if (result){
            res.json({
                code: 200
            })
        }
    }).catch(e=>{
        console.log(e)
    })
}

// 删除图书:按id删除
exports.deleteBook = function (req,res){
    let id = req.query.bookId

    BookDao.removeBook(id).then(result=>{
        if (result){
            res.json({
                code: 200
            })
        }
    }).catch(e=>{
        console.log(e)
    })
}

// 查询所有
exports.findAll = function (req,res){
    BookDao.queryAllBook().then(result=>{
        res.json({
            code: 200,
            info: result
        })
    })
}
//routes/BookApi.js

const express = require('express')
const router = express.Router()

const BookService = require('../service/BookService')

//增加图书接口:http://localhost:8088/books/add
router.post('/add',BookService.addBook)

//删除图书接口:http://localhost:8088/books/del
router.delete('/del',BookService.deleteBook)

//查询图书接口: http://localhost:8088/books/all
router.get('/all',BookService.findAll)

module.exports = router

       前端:

//src/axios/axiosaianstance.js

import axios from "axios";

const axiosInstance = axios.create({
    baseURL:  'http://localhost:8088',
    timeout: 5000
})

export default  axiosInstance
//src/componenrs/Book.vue

<template>
   <div>
     <table border="1" align="center">
       <thead>
          <tr>
            <th width="100">编号</th>
            <th width="300">名称</th>
            <th width="100">作者</th>
            <th width="200">出版日期</th>
            <th width="100">单价</th>
          </tr>
       </thead>
       <tbody>
          <tr v-for="(book,index) in bookList " :key="index">
            <td>{{ book.bookId }}</td>
            <td>{{ book.bookName }}</td>
            <td>{{ book.bookAuthor }}</td>
            <td>{{ book.bookDate }}</td>
            <td>{{ book.bookPrice }}</td>
          </tr>
       </tbody>
     </table>
     <hr/>
     <div>
       <label>
         图书名称:<input type="text" v-model="book_name">
       </label>
       <br/><br/>
       <label>
         图书作者:<input type="text" v-model="book_author">
       </label>
       <br/><br/>
       <label>
         出版日期:<input type="date" v-model="book_date">
       </label>
       <br/><br/>
       <label>
         图书单价:<input type="number" v-model="book_price">
       </label>
       <br/><br/>
       <button type="button" @click="addBook">增加</button>
     </div>
     <hr/>
     <label>
       图书编号:<input type="text" v-model="book_id">
     </label>
     <button type="button" @click="delBook">删除</button>
   </div>
</template>

<script>
import $http from '../axios/axiosInstance'
export default {
  name: "Book",
  data(){
    return {
      bookList: [],
      book_name: '',
      book_author:'',
      book_date: '',
      book_price:0,
      book_id:''
    }
  },
  methods: {
    getBooks(){
      $http.get('/books/all').then(res=>{
        this.bookList = res.data.info
      }).catch(e=>{
        console.log(e)
      })
    },
    addBook(){
      $http.post('/books/add',{
        bookName: this.book_name,
        bookAuthor: this.book_author,
        bookDate: this.book_date,
        bookPrice: this.book_price
      }).then(res=>{
        if (res.data.code == 200){
          this.getBooks()
          this.book_name= ''
          this.book_author =''
          this.book_date = ''
          this.book_price = 0
        }
      }).catch(e=>{
        console.log(e)
        alert('操作失败!')
      })
    },
    delBook(){
      $http.delete('/books/del',{
        params: {
          bookId: this.book_id
        }
      }).then(res=>{
        if (res.data.code == 200){
          this.getBooks()
          this.book_id = ''
        }
      }).catch(e=>{
        console.log(e)
        alert('操作失败!')
      })
    }
  },
  created() {
    this.getBooks()
  }
}
</script>

<style scoped>

</style>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/79739.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!