Vue學習筆記十三:Vue+Bootstrap+vue-resource從接口獲取數據庫數據


前言

Vue學習筆記九的列表案例和Vue學習筆記十二vue-resource這兩章結合一下,不在使用假數據了,這次從后台接口獲取json數據。

Vue前端框架提供交互邏輯處理

Bootstrap前端css提供美化渲染

SpringBoot后端提供接口

MySQL數據庫提供數據

SpringBoot提供后端接口

由於前端第九章我都寫完了,等會復制着用,所以先把后端寫好

先使用Spring JPA創建Entity類和自動映射數據庫表,JPA參考我的文章Spring JPA學習筆記

Entity類

package com.vae.weatherforecast.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.persistence.*;

@Entity
@Table(name = "person")
@AllArgsConstructor  //全參數的構造函數
@NoArgsConstructor   //無參數的構造函數
@Data              //get和set方法
@Accessors(chain = true)  //鏈式訪問,使用鏈式創建的set方法有返回值
@SuppressWarnings("serial")  //忽略黃色警告
public class test {
    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;
    private String name;
    private String createtime;
}

JPA操作接口

package com.vae.weatherforecast.repository;

import com.vae.weatherforecast.bean.test;
import org.springframework.data.jpa.repository.JpaRepository;

public interface testRepository extends JpaRepository<test,Integer> {

}

配置文件

JPA的配置文件寫在了properties里,其他的寫在了yml里

server:
  port: 80

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/vae?serverTimezone=UTC
    username: root
    password: 123
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

數據庫表自動映射,添加數據

運行SpringBoot,會自動創建表,現在來添加一些數據,如圖

寫提供數據的接口

新建controller,寫幾個操作數據的接口,我先寫一個提供數據的接口,至於增刪改查的增刪改,下面再寫。

    @Autowired
    testRepository testRepositorynew;

    @CrossOrigin
    @GetMapping("/getAllList")
    public List<test> getAllList() {
        List<test> lists = testRepositorynew.findAll();
        for (test testnew : lists) {
            System.out.println(testnew);
        }
        return lists;
    }

跨域問題

使用Vue訪問自己提供的接口的時候,會出現跨域問題的,解決辦法很簡單啊,SpringBoot為我們考慮了很多,直接在方法上加一個@CrossOrigin就可以了,這里注意寫@GetMapping,Vue那里也使用get方式。至於jsonp方式我還不知道怎么使用。

前端修改

復制第九章的代碼,修改后如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蜀雲泉</title>
    
    <script type="text/javascript" src="../lib/vue-2.6.10.js"></script>
    <script type="text/javascript" src="../lib/vue-resource.min.js"></script>
    <link rel="stylesheet" href="../lib/bootstrap.min.css">

</head>
<body>
    
    <!-- 這個div就是MVVM中的V,View -->
    <div id="app">

        <!-- 自定義按鍵碼 -->
        <!-- Vue.config.keyCodes.F2=113 -->
        
        
        <div class="panel panel-primary">
              <div class="panel-heading">
                    <h3 class="panel-title">蜀雲泉的小列表</h3>
              </div>
              <!-- form-inline是文字和輸入框在同一行顯示,form-control是設置默認寬度width為100% -->
              <div class="panel-body form-inline">
                  <label>
                      id:<input type="text" class="form-control" v-model="id">
                  </label>
                  <label>
                      name:<input type="text" class="form-control" v-model="name" @keyup.enter="add">
                  </label>

                  <input type="button" value="添加" class="btn btn-primary" @click="add">

                  <label>
                        查詢:<input type="text" class="form-control" v-model="keywords" v-focus v-color="'blue'">
                  </label>

              </div>
        </div>
        
        
        
        <table class="table table-bordered table-hover table-striped">
            <thead>
                <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>createtime</th>
                    <th>operation</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in search(keywords)" :key="item.id">
                    <td v-text="item.id"></td>
                    <td v-text="item.name"></td>
                    <td v-text="item.createtime"></td>
                    <td><a href="" @click.prevent="del(item.id)" class="btn btn-danger">刪除</a></td>

                </tr>
            </tbody>
        </table>
        
        
        

    </div>


    <script>

        // 自定義全局的指令
        Vue.directive('focus',{
            // 第一個參數一定是el,el就是被綁定的js對象

            // 當指令綁定到元素上的時候,執行bind函數,執行一次
            bind:function(el){
                
            },
            // 當指令插入到DOM中的時候,執行inserted函數,執行一次
            inserted:function(el){
                el.focus()
            },
            // 當組件更新的時候,執行updated函數,可能會執行多次
            updated:function(el){

            }
        })


        // 這個vm就是MVVM中的VM,ViewModel
        var vm=new Vue({
         el: '#app',
        //  這個data就是MVVM中的M,Model
         data: {
             id:'',
             name:'',
             keywords:'', 
             list:[]
         },
         created() {
             //在Vue加載的時候執行
             this.getAllList()
         },
         methods: {
             getAllList(){
                this.$http.get('http://localhost/getAllList').then(result=>{
                    console.log(result)
                     //成功了的回調函數
                     if(result.status===200){
                         this.list=result.body
                     }
                     else{
                         alert('獲取數據失敗!')
                     }
                })
             },
             add(){
                 this.list.push({id:this.id,name:this.name,creattime:new Date().toLocaleString()})
             },
             del(id){
                var index=this.list.findIndex(item=>{
                    if(item.id==id)
                    return true
                })
                this.list.splice(index,1)
      
             },
             search(keywords){
                return this.list.filter(item=>{
                    if(item.name.includes(keywords))
                    return item
                })
             }

         },
         directives:{
             "color":{
                 bind:function(el,binding){
                     el.style.color=binding.value
                 }
             }
         }  

        })

    </script>

</body>
</html>

可以看到我沒有使用假數據,使用了新學的vue-resource,get方式。這里遭遇的跨域請求已經在上面解釋過了。

效果圖

看看效果圖

已經成功的從后台獲取了數據,其實很簡單,獲取數據的接口已經完成了,那么接下來的刪除,增加也很簡單。

待續

待續...

我突然發現vue-resource已經不被官方推薦了....官方推薦的是axios.....

這篇文章我還是按照vue-resource來一個完整的增刪改查,然后axios也來一版吧

防盜鏈接:本博客由蜀雲泉發表


免責聲明!

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



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