使用Node+Vue實現簡單CRUD

前言

在上一篇寫的數據庫的增刪改查用的是node模塊寫的客戶端,此次寫一個純前端發起請求與後端的交互。 用到的技術主要是Vue+ElementUi+Axios作前端,NodeJs+Express+Mysql寫後端接口。css

準備工做

vue

初始化一個vue項目前端

sudo cnpm install --global vue-cli
cnpm install webpack -g
vue init webpack my-project
cd my-project
cnpm install
cnpm run dev
複製代碼

安裝依賴插件

cnpm install express body-parser --save
cnpm install element-ui --save
npm install axios --save
複製代碼

ElementUi使用vue

import "element-ui/lib/theme-chalk/index.css"
import ElementUI from "element-ui"
Vue.use(ElementUI)
複製代碼

Mysql db.js node

完成sql語句映射

後端

// node 後端服務器

const userApi = require('./api/userApi');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 後端api路由
app.use('/api/user', userApi);

// 監聽端口
app.listen(3000);
console.log('監聽端口 :3000');

複製代碼

查詢接口

//根據條件查詢用戶接口
router.get('/queryUser', (req, res) => {
    var sql = $sql.user.select;
    var params = req.query;
    console.log(params);
    conn.query(sql, [params.queryParam], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            res.send(result);
        }
    })
});
//返回所有數據接口,一開始進來就進行加載
router.get('/allUser', (req, res) => {
    var sql = $sql.user.selectAll;
    conn.query(sql, function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            res.send(result);
        }
    })
});
複製代碼

用戶一進入頁面用戶數據會所有請求一次,這裏數據是按姓名查詢的

增長接口

// 增長用戶接口
router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;
    var params = req.body;
    console.log(params);
    conn.query(sql, [params.username, params.age,params.address], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            res.send(result);
        }
    })
});
複製代碼

這裏增長用戶的姓名,年齡,地址, ID是自增加的webpack

更改接口

//修改用戶數據接口
router.patch('/patchUser', (req, res) => {
    var sql = $sql.user.update;
    var params = req.body;
    console.log(params);
    conn.query(sql, [params.username, params.age,params.address,params.id], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            res.send(result);
        }
    })
});
複製代碼

刪除接口

//刪除用戶接口
router.delete('/deleteUser', (req, res) => {
    var sql = $sql.user.delete;
    console.log(req)
    var params = req.query;
    console.log(params);
    conn.query(sql, [params.id], function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            res.send(result);
        }
    })
});
複製代碼

前端傳入相應要刪減的用戶ID,後端根據參數操做數據庫,刪除相應用戶數據ios

前端

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div class="searchBox">
      <el-input
        class="search"
        type="text"
        name="queryParam"
        v-model="queryParam"
        placeholder="輸入關鍵字搜索"
      ></el-input>
      <el-button type="primary" @click="queryUser">查詢</el-button>
    </div>
    <form ref="formbox">
      <el-input type="text" name="username" v-model="userName" placeholder="請輸入姓名" ref="input1"></el-input>
      <br>
      <el-input type="text" name="age" v-model="age" placeholder="請輸入年齡" class="mt10"></el-input>
      <br>
      <el-input type="text" name="address" v-model="address" placeholder="請輸入地址" class="mt10"></el-input>
      <br>
      <el-button type="primary" @click="addUser" class="mt10">添加</el-button>
    </form>
    <el-table
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 60%;margin: 0 auto"
    >
      <el-table-column label="Id" prop="id"></el-table-column>
      <el-table-column label="Name" prop="name"></el-table-column>
      <el-table-column label="Age" prop="age"></el-table-column>
      <el-table-column label="Address" prop="address"></el-table-column>
      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showDialog(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index+1, scope.row)">刪除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--彈窗數據-->
    <el-dialog title="提交修改信息" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-input type="text" name="username" v-model="userName2" placeholder="請輸入姓名" ref="input1"></el-input>
      <br>
      <el-input type="text" name="age" v-model="age2" placeholder="請輸入年齡" class="mt10"></el-input>
      <br>
      <el-input type="text" name="address" v-model="address2" placeholder="請輸入地址" class="mt10"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit">確 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
...

複製代碼

這裏前端主要用的前端UI框架ElementUi,作view展現web

查詢數據

queryUser () {
      var queryParam = this.queryParam;
      axios
        .get("api/user/queryUser", {
          params: {
            queryParam: queryParam
          }
        })
        .then(response => {
          console.log(response);
          // this.user = response.data;
          var resdata = response.data;
          this.tableData = resdata;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    queryallUser () {
      axios
        .get("api/user/allUser")
        .then(response => {
          // console.log(response);
          var resdata = response.data;
          this.tableData = resdata;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
複製代碼

從後端請求來的數據賦給來了this.tableData,直接渲染到頁面上sql

增長數據

addUser () {
      var name = this.userName;
      var age = this.age;
      var address = this.address;
      axios
        .post("api/user/addUser", {
          username: name,
          age: age,
          address: address
          // address: address
        })
        .then(response => {
          console.log(response);
          //增長數據成功後會執行open2函數彈出成功提示
          this.open2();
          //添加數據成功後,清空input框的數據
          this.userName = "";
          this.age = "";
          this.address = "";
        })
        .catch(function (error) {
          console.log(error);
        });
    },
複製代碼

更改數據

handleEdit () {
    //獲取相應要更改的ID
      var id = parseInt(this.objId.id);
      console.log(id)
      //獲取更改後的內容
      var name = this.userName2;
      var age = this.age2;
      var address = this.address2;
      axios
        .patch("api/user/patchUser", {
        //傳遞的參數
          username: name,
          age: age,
          address: address,
          id: id
        })
        .then(response => {
          console.log(response);
          //這裏有一個天寫更改內容的彈窗,更改內容成功後,彈窗消失,數據清空
          this.dialogVisible = false;
          this.userName2 = "";
          this.age2 = "";
          this.address2 = "";
        })
        .catch(function (error) {
          console.log(error);
        });
    },
複製代碼

根據ID,更改相應用戶的數據,把內容和條件一塊兒傳遞過去。
這裏update: 'update userinfo set name=? , age=? , address=? where id=?'語句不寫and 鏈接vue-cli

刪除數據

handleDelete (index, row) {
      console.log(row);
      var id = row.id;
      console.log(id);
      axios
        .delete("api/user/deleteUser", {
          params: {
            id: id
          }
        })
        .then(response => {
          console.log(response);
          //執行成功,給予刪除成功提示
          this.open3();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
複製代碼

把要刪除的用戶ID做爲參數傳遞過去,服務端根據ID操做數據庫,刪除相應用戶數據。數據庫

跨域

前端請求數據,不得不提跨域問題,在 config>index.js 的 dev 中添加配置項 proxyTable:

相關文章
相關標籤/搜索