前後端分離專案(十):實現"改"功能(前後端)

2022-11-02 06:00:26

好傢伙,本篇介紹如何實現"改"

我們先來看看效果吧

 (這可不是假資料喲,這是真資料喲)

 (忘記錄滑鼠了,這裡是點了一下重新整理)

 

First Of All 

我們依舊先來理一下思路:

首先在"管理"頁面中,我能看到所有的書本資訊,

隨後,在每一個資訊後都有對應的"修改按鈕"

當我點選這個按鈕時,我要①拿到這個這條資料的id($router傳參)

然後②跳轉到"資訊修改介面",(這個介面會像書本新增的那個介面一樣,有兩個輸入框,一個提交按鈕,一個重置按鈕)

這時,我向後端③請求到當前這條"id"的相關資料(舉例:{id:1,name:三體1,auther:劉慈欣})

將它展示到"資訊修改介面"的輸入框中,隨後,你可以將這些資料根據你想要的形狀進行修改

最後點選修改資料,④傳送axios請求到後端提交更新後的資料

 

思路清晰,開幹

目錄如下:

這裡我們只需用到MyUsers.vue元件(書本管理頁)和MyGoods.vue元件(書本修改頁),

 

當然了,我們要先把這個資訊修改介面寫(CV)出來

MyGoods元件如下

這裡我們選擇讓id唯讀,不允許修改 

MyGoods.vue程式碼如下:

<!-- 該元件為書本修改功能元件 -->
<template>
  <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="圖書編號" prop="id">
          <el-input v-model="ruleForm.id" readonly=""></el-input>
      </el-form-item>

      <el-form-item label="圖書名稱" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="作者" prop="author">
          <el-input v-model="ruleForm.author"></el-input>
      </el-form-item>

      <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>

  </el-form>
</template>

<script>
import axios from 'axios'
  export default {
      data() {
          return {
              ruleForm: {
                  id: '',
                  name: '',
                  author: ''
              },
              rules: {
                  name: [
                      { required: true, message: '圖書名稱不能為空', trigger: 'blur' }
                  ],
                  author:[
                      { required: true, message: '作者不能為空', trigger: 'blur' }
                  ]
              }
          };
      },
      methods: {
          submitForm(formName) {
              const _this = this
              this.$refs[formName].validate((valid) => {
                  if (valid) {
                      axios.put('http://localhost:8011/book/update',this.ruleForm).then(function(resp){
                          if(resp.data == 'success'){
                              _this.$alert(''+_this.ruleForm.name+'》修改成功!', '訊息', {
                                  confirmButtonText: '確定',
                                  callback: action => {
                                      _this.$router.push('/home/users')
                                  }
                              })
                          }
                      })
                  } else {
                      return false;
                  }
              });
          },
          resetForm(formName) {
              this.$refs[formName].resetFields();
          }
      },
      created(){
        const _this=this
        alert(this.$route.query.id)
        axios.get('http://localhost:8011/book/findById/'+this.$route.query.id).then(function(resp){
          _this.ruleForm =resp.data
        })
      
  }
}
</script>

 

MyUsers.vue程式碼如下:

<!-- 該元件為表單主要元件 -->
<template>
  <div>
    <!-- 標題 -->
    <h4 class="text-center">使用者管理</h4>
    <!-- 使用者新增按鈕 -->
    <el-col :span="4">
      <el-button type="primary" @click="addDialogVisible = true">新增使用者</el-button>
    </el-col>
    <!-- 使用者列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="序號" width="180">
      </el-table-column>
      <el-table-column prop="name" label="書名" width="180">
      </el-table-column>
      <el-table-column prop="author" label="作者" width="180">

      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">修改</el-button>
          <el-button @click="Bookdelete(scope.row)" type="text" size="small">刪除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination :page-size="6" :pager-count="11" layout="prev, pager, next" :total="total" @current-change="page">
    </el-pagination>
    <!-- <el-pagination :page-size="20" 
    :pager-count="11" 
    layout="prev, pager, next" 
    :total="18"
    @current-change="page" >
    </el-pagination> -->
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MyUser',
  data() {
    return {
      total: null,
      // 使用者列表資料
      tableData: [
        { id: '1', name: '三體1', author: '大劉' },
        { id: '2', name: '三體2', author: '大劉' },
      ],
      addDialogVisible: false, //控制新增使用者對話方塊的顯示與隱藏
      addUserForm: {},
      //新增表單的驗證規則物件
      addUserFormRules: {
        // username: [{required:true,message:'請輸入使用者名稱',trigger:'blur'},
        // {min:3,max:10,message:'使用者名稱長度在3~10個字元',trigger:'blur'}],
        // password: [{required:true,message:'請輸入密碼',trigger:'blur'},
        // {min:6,max:15,message:'密碼長度在6~15個字元',trigger:'blur'}],
        // email: [{required:true,message:'請輸入郵箱',trigger:'blur'}],
        // mobile: [{required:true,message:'請輸入手機號',trigger:'blur'}]
      }
    }
  },
  methods: {
    //書本刪除方法
    Bookdelete(row) {
      const _this = this
      axios.delete('http://localhost:8011/book/deleteById/' + row.id).then(() => {
        _this.$alert('' + row.name + '》刪除成功!', '訊息', {
          confirmButtonText: '確定',
          callback: action => {
            window.location.reload()
          }
        })
      })
    },
    //頁面點選修改按鈕
    handleClick(row) {
      console.log(row);
      this.$router.push({
        path: "goods",
        query: {
          id: row.id
        }
      })
    },
    //分頁方法
    page(currentPage) {
      const _this = this;
      axios.get('http://localhost:8011/book/findAll/' + currentPage + '/6').then(function (resp) {
        _this.tableData = resp.data.content
        _this.total = resp.data.totalElements

        console.log(resp.data)
      })
    }

  },
  created() {
    const _this = this;
    axios.get('http://localhost:8011/book/findAll/1/6').then(function (resp) {
      _this.tableData = resp.data.content
      _this.total = resp.data.totalElements

      console.log(resp.data)
    })
  }

}
</script>

<style lang="less" scoped>

</style>

(別忘了配路由,你已經是個成熟的cv程式設計師了,要學會自己配路由)

後端的介面:

package com.example.demo2.controller;

import com.example.demo2.entity.Book;
import com.example.demo2.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/book")
public class BookHandler {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageRequest request = PageRequest.of(page-1,size);
        return bookRepository.findAll(request);
    }

    @PostMapping("/save")
    public String save(@RequestBody Book book){
        Book result = bookRepository.save(book);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result = bookRepository.save(book);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);
    }
}

 

來吧

1.拿到這個這條資料的id

<template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">修改</el-button>
          <el-button @click="Bookdelete(scope.row)" type="text" size="small">刪除</el-button>
</template>

對應方法:

//頁面點選修改按鈕
    handleClick(row) {
      console.log(row);
      this.$router.push({
        path: "goods",
        query: {
          id: row.id
        }
      })
    },

 

 

2.跳轉到"資訊修改介面"

this.$router.push({
        path: "goods",
        query: {
          id: row.id
        }
      })
query:用來傳參的一個屬性


3.請求到當前這條"id"的相關資料,並將它展示到"資訊修改介面"的輸入框中

created(){
        const _this=this
        alert(this.$route.query.id)
        axios.get('http://localhost:8011/book/findById/'+this.$route.query.id).then(function(resp){
          _this.ruleForm =resp.data
        })
      
  }

 

 

4.傳送axios請求到後端提交更新後的資料

submitForm(formName) {
              const _this = this
              this.$refs[formName].validate((valid) => {
                  if (valid) {
                      axios.put('http://localhost:8011/book/update',this.ruleForm).then(function(resp){
                          if(resp.data == 'success'){
                              _this.$alert('《'+_this.ruleForm.name+'》修改成功!', '訊息', {
                                  confirmButtonText: '確定',
                                  callback: action => {
                                      _this.$router.push('/home/users')
                                  }
                              })
                          }
                      })
                  } else {
                      return false;
                  }
              });
          },

注意此處用的是put請求

 

搞定啦!(激動)