springboot整合vue04-前后端數據交互


1.分頁列表
打開elementui官網,地址: https://element.eleme.cn/#/zh-CN
找一個看順眼的列表拷貝代碼到vue工程;
 
然后找一個看順眼的分頁組件,拷貝代碼到vue工程;
 
后台提供一個分頁接口
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookRepository books;
 
    @GetMapping("/query/{page}/{size}")
    public Page<Book> query(@PathVariable("page")Integer page,
                            @PathVariable("size")Integer size
        ){
        //封裝一個分頁對象
        PageRequest pageRequest = PageRequest.of(page, size);
        //findAll的重載方法,傳入一個PageRequest對象,返回一個Page對象
        return books.findAll(pageRequest);
    }
}
 
前端用axios做get請求分頁接口
需要在created事件中請求;
<template>
    <div>
        <!--列表-->
        <el-table
        :data="books"
        border
        style="width: 100%">
        <el-table-column
          fixed
          prop="id"
          label="編號"
          width="120">
        </el-table-column>
        <el-table-column
          prop="name"
          label="書名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="author"
          label="作者"
          width="120">
        </el-table-column>
        <el-table-column
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
            <el-button type="text" size="small">編輯</el-button>
          </template>
        </el-table-column>
      </el-table>
 
        <!--分頁組件-->
        <el-pagination
          background
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="page"
          :total="total">
        </el-pagination>
    </div>
</template> 
 
<script>
  export default {
    name:'PageOne',
    methods: {
      handleClick(row) {
        console.log(row);
      },
      page(currentPage){
          const _this = this;
          axios.get("http://localhost:8090/book/query/"+(currentPage - 1)+"/5").then(function (resp) {
              _this.books=resp.data.content;
              _this.total=resp.data.totalElements;
              _this.pageSize=resp.data.size;
          })
      }
    },
 
    data() {
      return {
        books: [{
          id: '1',
          name: '他改變了季漢',
          author: '諸葛村夫',
        }, {
            id: '2',
            name: '歷史選擇了曹老板',
            author: '王司徒',
        }, {
            id: '3',
            name: '劉黃書最后的革命',
            author: '小懿子',
        }],
        pageSize:'1',
        total:'10',
          
      }
    },
    created(){
        const _this = this;
        axios.get("http://localhost:8090/book/query/0/5").then(function (resp) {
            _this.books=resp.data.content;
            _this.total=resp.data.totalElements;
            _this.pageSize=resp.data.size;
        })
    }
 
  }
</script>
 
頁面效果:
 
2.新增數據
在elementui官網找一個合適的表單,拷貝代碼到vue工程,根據需要修改
 
后台增加一個插入數據的web接口:
@Autowired
private BookRepository books;
 
@RequestMapping("/add")
public String add(@RequestBody Book book){
    Book res = books.save(book);
    if(res != null){
        return "success";
    }else{
        return "error";
    }
}
 
然后在vue工程中調用后台接口:
<template>
    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <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>
    </div>
</template>
 
<script>
      export default {
        name:'PageTwo',
        data() {
          return {
            ruleForm: {
              name: '',
              author: ''
            },
            rules: {
              name: [
                { required: true, message: '請輸入書名', trigger: 'blur' },
                { min: 1, max: 10, message: '長度在 1 到 10 個字符', trigger: 'blur' }
              ],
              author: [
                { required: true, message: '請輸入作者', trigger: 'blur' }
              ]
            }
          };
        },
        methods: {
          submitForm(formName) {
            const _this = this;   //取vue對象
            this.$refs[formName].validate((valid) => {
              if (valid) {
                //ajax請求
                axios.post("http://localhost:8090/book/add", this.ruleForm).then(function (resp) {
                  if(resp.data == 'success'){
                    _this.$router.push("/p1");  //添加成功跳到列表頁
                  }else{
                      alert("error");
                  }
                });
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          }
        }
      }
    </script>

  

3.編輯數據
需要先跳到詳情頁面,然后編輯,因此需要前端提供一個詳情頁面;
需要后端提供兩個接口分別用來通過該id查詢、保存編輯;
 
1)后端接口:
//通過id查詢
@GetMapping("/get/{id}")
public Book get(@PathVariable("id")Integer id){
    return books.findById(id).get();
}
 
//編輯
@RequestMapping("/edit")
public String edit(@RequestBody Book book){
    Book res = books.save(book);
    if(res != null){
        return "success";
    }else{
        return "error";
    }
}
 
2)跳轉到編輯頁面
點擊編輯按鈕,要跳到編輯頁面,並且將當前行的id傳過去,用來通過id請求后台獲取詳情數據;
 
編輯按鈕:
<template slot-scope="scope">
  <el-button @click="handleClick(scope.row)" type="text" size="small">刪除</el-button>
  <el-button @click="toEdit(scope.row)" type="text" size="small">編輯</el-button>
</template>  
分析拷貝過來的列表代碼,可以看出來:<template slot-scope="scope">標簽下可以用scope.row取到當前行的信息;
用click事件綁定toEdit方法,傳入的參數為列表的row;
得到了row,就能通過row.id取到當前行的id;
 
在method中添加一個toEdit方法用來跳轉到編輯頁面:
toEdit(row){        //跳轉到編輯頁,並且將選中行的id傳過去
    this.$router.push({
        path:'/p3',
        query:{
            id:row.id
        }
    })
}  
這里是用$router.push跳到編輯頁的路由,需要在router目錄下給編輯頁面配置路由;
 
3)編輯頁面
這個頁面和新增數據頁面類似,可以直接拷貝代碼過去,適當修改即可;
需要在created事件中接收傳過來的id,並且請求后台得到數據然后填到表單中;
可以用$route.query來得到傳過來的參數;(一般$route用來取參數,而$router用來做跳轉)
created(){
    const _this = this;
    var id = this.$route.query.id;
    if(id > 0){
        axios.get("http://localhost:8090/book/get/" + id).then(function (resp) {
            _this.ruleForm = resp.data;
        })
    }
} 
 
做完表單填充后,還需要做保存編輯;
包括幾個步驟:
    一個ajax提交表單,請求后台的編輯接口;
    保存成功后調回分頁列表;
methods: {
  submitForm(formName) {
    const _this = this;   //取vue對象
    this.$refs[formName].validate((valid) => {
      if (valid) {
        //ajax請求
        axios.post("http://localhost:8090/book/edit", this.ruleForm).then(function (resp) {
          if(resp.data == 'success'){
            _this.$router.push("/p1");  //添加成功跳到列表頁
          }else{
              alert("error");
          }
        });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  },
  resetForm(formName) {
    this.$refs[formName].resetFields();
  },
},
 
4.刪除
1)后台提供一個刪除接口:
@GetMapping("/del/{id}")
public void delete(@PathVariable("id")Integer id){
    books.deleteById(id);
}
 
2)前端
給列表的刪除操作綁定一個delete方法;
通過scope.row可以去到目標行的id;
然后用id做參數用axios請求后台;
刪除完成后刷新列表;
 
為了防止誤刪,可以加一個提示彈框;
在elementui中找一個好看的彈框,將代碼拷過來;
主要代碼:
del(row){
   const _this = this;
   _this.$confirm('此操作將永久刪除該文件, 是否繼續?', '提示', {
   confirmButtonText: '確定',
   cancelButtonText: '取消',
   type: 'warning'
  }).then(() => {
    axios.get("http://localhost:8090/book/del/"+row.id).then(function (resp) {
        _this.$message({
          type: 'success',
          message: '刪除成功!'
        });
        window.location.reload(); //刷新頁面
    });
 
  }).catch(() => {
    this.$message({
      type: 'info',
      message: '已取消刪除'
    });
  });
}

  

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM