Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,基本请求有5种: 

  • get:多用来获取数据
  • post:多用来新增数据
  • put:多用来修改数据(需要传递所有字段,相当于全部更新)
  • delete:多用来删除数据

 注 : get、delete请求的参数是params(特殊情况可以直接跟在地址后面),而post、put的参数是data

下载js:js/vue-2.6.12.js     js/axios-0.21.0.js

链接:https://pan.baidu.com/s/1US7jEn3bmCJBsPoxpPAsUQ?pwd=uj8u 
 

引入:组件库、样式(html文件跟js文件在同一目录下)

<!-- 引入样式 -->
    <script src="js/vue-2.6.12.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="js/axios-0.21.0.js"></script>

get请求分页查全部:HTML的axios

<script>
axios({
                    method: 'get', //请求类型为get
                    url: "http://localhost:8989/springboot/computer/1/5", //请求地址
                }).then((resp) => {
                    this.page = resp.data  //后端传值处理
                    this.page.pageSizes = [3, 5, 10],  //分页的每页显示行数
                        this.page.pageCount = 5      //分页的下端显示几个页码
                })
</script>

get请求分页查全部:Controller

@RestController
@RequestMapping("/computer")
public class ComputerController {
    @Autowired
    private ComputerService computerService;

    @GetMapping("/{pageNum}/{pageSize}")
    public PageInfo<Computer> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
        return computerService.selectAll(pageNum,pageSize);
    }
}

get请求分页查全部:Service

@Service
public class ComputerServiceImpl implements ComputerService {
    @Autowired
    private ComputerMapper mapper;
    @Override
    public PageInfo<Computer> selectAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Computer> phones = mapper.selectAll();
        PageInfo<Computer> page = new PageInfo<>(phones);
        return page;
    }
}

get请求分页查全部:Mapper

@Mapper
public interface ComputerMapper {
    public List<Computer> selectAll();
}
<mapper namespace="com.jia.mapper.ComputerMapper">
    <resultMap id="computerMap" type="com.jia.entity.Computer">
        <id column="id" property="id"/>
        <result column="price" property="price"/>
        <result column="screen" property="screen"/>
        <result column="keyboard" property="keyboard"/>
        <result column="mouse" property="mouse"/>
        <result column="color" property="color"/>
        <result column="clang" property="clang"/>
        <association property="brand" javaType="com.jia.entity.Brand">
            <id column="bid" property="brandId"/>
            <result column="bname" property="brandName"/>
        </association>
    </resultMap>

    <select id="selectAll" resultMap="computerMap">
        SELECT c.*,b.brand_id bid,b.brand_name bname FROM t_computer c LEFT OUTER JOIN t_brand b on c.brand_id = b.brand_id
    </select>
</mapper>

put添加:html

<script>
axios({
                        method: "Put",
                        url:"http://localhost:8989/springboot/computer/",
                        data:this.computer  //请求体传参
                    }).then((resp)=>{
                        computer:{
                            brand:{}
                        };
                        this.toSelectAll()  
                        this.showUpdateForm=false;
                    })
</script>

put添加:controller

@PutMapping("/")
    public void update(@RequestBody Computer computer){
        System.err.println(computer);
        computerService.updateById(computer);
    }

post修改:html

<script>
axios.post("http://localhost:8989/springboot/computer/",this.computer).then((resp)=>{
                        computer:{
                            brand:{}
                        };
                        this.toSelectAll()
                        this.showUpdateForm=false;
                    })
</script>

post修改:controller

@PostMapping("/")
    public void addComputer(@RequestBody Computer computer){
        System.err.println(computer);
        computerService.addComputer(computer);
    }

根据id的delete删除:html

<script>
axios({
                    method: "delete",
                    url:"http://localhost:8989/springboot/computer/"+id,
                    // params:{
                    //     id:id
                    // }
                }).then(()=>{
                    this.toSelectAll()
                })
</script>

根据id的delete删除:controller

@GetMapping("/{id}")
    public Computer selectById(@PathVariable("id") int id){
        return computerService.selectById(id);
    }

批量删除:html

<script>
axios({
                    method:'delete',
                    url:'http://localhost:8989/springboot/computer/',
                    data:this.ids
                }).then((resp)=>{
                    this.toSelectAll()
                })
</script>

批量删除:controller

@DeleteMapping("/")
    public void deletes(@RequestBody int [] ids){
        for (int id : ids) {
            System.err.println(id);
        }
        computerService.deletes(ids);
    }

完整的html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入样式 -->
    <script src="js/vue-2.6.12.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="js/axios-0.21.0.js"></script>

</head>
<body>
<div id="app">
    <div>
        <el-button type="primary" @click="toShowAddForm">添加</el-button>
        <el-table
                :data="page.list"
                style="width: 100%"  border
                stripe
                @selection-change="getIds">
            <el-table-column
                    header-align="center"
                    align="center"
                    type="selection"
            ></el-table-column>
            <el-table-column
                    header-align="center"
                    align="center"
                    label="序号"
                    type="index"
                    width="100"
            >
            </el-table-column>
            <el-table-column
                    prop="id"
                    label="主键"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="price"
                    label="价格"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="screen"
                    label="屏幕"
                    width="100"
                    >
            </el-table-column>
            <el-table-column
                    prop="keyboard"
                    label="键盘">
            </el-table-column>
            <el-table-column
                    prop="mouse"
                    label="鼠标">
            </el-table-column>
            <el-table-column
                    prop="color"
                    label="颜色">
            </el-table-column>
            <el-table-column
                    prop="clang"
                    label="音响">
            </el-table-column>
            
           
            <el-table-column
                    prop="brand.brandName"
                    label="品牌">
            </el-table-column>
            <el-table-column
                    header-align="center"
                    align="center"
                    label="操作"
            >
                <!-- 自定义列模板-->
                <template slot-scope="scope">
                    <el-button type="warning" @click="toShowUpateForm(scope.row.id)">修改</el-button>
                    <el-button type="danger" @click="toDeleteById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination layout="sizes, prev, pager, next, jumper, ->, total" :total="page.total"
            :page-size.sync="page.pageSize" :page-sizes="page.pageSizes" :current-page.sync="page.pageNum"
            :pager-count="page.pagerCount" @size-change="toSelectByPageForChangePageSize"
            @current-change="toSelectByPageForChangePageNum" background>
        </el-pagination>
        <el-button type="danger" @click="toDeleteMany">删除选中</el-button>
        <el-dialog :title="title" :visible.sync="showUpdateForm">
            <el-form ref="form" :model="computer" label-width="80px">
                <el-form-item label="价格">
                    <el-input type="text" v-model="computer.price"/>
                </el-form-item>
                <el-form-item label="屏幕">
                    <el-input type="text" v-model="computer.screen"/>
                </el-form-item>
                <el-form-item label="键盘">
                    <el-input type="text" v-model="computer.keyboard"/>
                </el-form-item>
                <el-form-item label="鼠标">
                    <el-input type="text" v-model="computer.mouse"/>
                </el-form-item>
                <el-form-item label="颜色">
                    <el-input type="text" v-model="computer.color"/>
                </el-form-item>
                <el-form-item label="音响">
                    <el-input type="text" v-model="computer.clang"/>
                </el-form-item>
               
                <el-form-item label="品牌">
                    <el-select v-model="computer.brand.brandId" placeholder="请选择">
                        <el-option
                                v-for="item in brands"
                                :key="item.value"
                                :label="item.brandName"
                                :value="item.brandId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="danger" @click="noShowUpateForm()">取消</el-button>
                    <el-button type="primary"  @click="UpdateForm(title)">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</div>
<script>
    const vm = new Vue({
        el:"#app",
        data:{
            computers:[
                 
            ],
            pageNum: 1,
            pageSize: 5,
            page: {
                    pageSizes: [3, 5, 10],
                    pagerCount: 5
                },
            ids:[],
            showUpdateForm:false,
            computer:{brand:{}},
             brands:[]
        },created(){
            axios({
                    method: 'get',
                    url: "http://localhost:8989/springboot/computer/1/5",
                    
                }).then((resp) => {
                    this.page = resp.data
                    this.page.pageSizes = [3, 5, 10],
                        this.page.pageCount = 5
                })
        }
        ,methods:{
            getIds(val){
                this.ids=[]
                for(var i = 0;i<val.length;i++){
                    this.ids.push(val[i].id)
                }
            },
            toSelectAll(){
                axios({
                    method: 'get',
                    url: "http://localhost:8989/springboot/computer/"+this.page.pageNum+"/"+this.page.pageSize,
                    
                }).then((resp) => {
                    this.page = resp.data
                    this.page.pageSizes = [3, 5, 10],
                        this.page.pageCount = 5
                })
            },toShowUpateForm(id){
                axios({
                    method: "get",
                    url:"http://localhost:8989/springboot/computer/"+id,
                    
                }).then((resp)=>{this.computer=resp.data})
                axios({
                    method: "get",
                    url:"http://localhost:8989/springboot/brand/",
                }).then((resp)=>{
                    this.brands=resp.data
                    this.title="修改"
                    this.showUpdateForm=true
                })

            }
            ,toShowAddForm(){
                this.computer={
                    brand:{}
                }
                axios({
                    method: "get",
                    url:"http://localhost:8989/springboot/brand/",
                }).then((resp)=>{
                    this.brands=resp.data
                    this.title="添加"
                    this.showUpdateForm=true
                })
            },
            noShowUpateForm(){
                this.computer={
                    brand:{}
                }
                this.showUpdateForm=false
            },
            UpdateForm(title){
                if (title=="添加"){
                    console.log(this.computer)
                 
                    axios.post("http://localhost:8989/springboot/computer/",this.computer).then((resp)=>{
                        computer:{
                            brand:{}
                        };
                        this.toSelectAll()
                        this.showUpdateForm=false;
                    })
                }else {
                    axios({
                        method: "Put",
                        url:"http://localhost:8989/springboot/computer/",
                        data:this.computer
                    }).then((resp)=>{
                        computer:{
                            brand:{}
                        };
                        this.toSelectAll()
                        this.showUpdateForm=false;
                    })

                }

            },
            toDeleteById(id){
                axios({
                    method: "delete",
                    url:"http://localhost:8989/springboot/computer/"+id,
                    
                }).then(()=>{
                    this.toSelectAll()
                })
            },toDeleteMany(){
                axios({
                    method:'delete',
                    url:'http://localhost:8989/springboot/computer/',
                    data:this.ids
                }).then((resp)=>{
                    this.toSelectAll()
                })
            },toSelectByPageForChangePageSize(pageSize) {
                    axios({
                        method: 'get',
                        url: "http://localhost:8989/springboot/computer/"+this.page.pageNum+"/"+pageSize,
                        
                    }).then((resp) => {
                        this.pageNum=resp.pageNum
                        this.pageSize=resp.pageSize
                        this.page = resp.data
                        this.page.pageSizes = [3, 5, 10],
                            this.page.pageCount = 5
                    })
                },
                toSelectByPageForChangePageNum(pageNum) {
                    axios({
                        method: 'get',
                        url: "http://localhost:8989/springboot/computer/"+pageNum+"/"+this.page.pageSize,
                        
                    }).then((resp) => {
                        this.pageNum=resp.pageNum
                        this.pageSize=resp.pageSize
                        this.page = resp.data
                        this.page.pageSizes = [3, 5, 10],
                            this.page.pageCount = 5
                    })
                }
        }
    })
</script>
</body>
</html>

完整的controller

package com.jia.controller;

import com.jia.entity.Computer;
import com.jia.service.ComputerService;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/computer")
public class ComputerController {
    @Autowired
    private ComputerService computerService;

    @GetMapping("/{pageNum}/{pageSize}")
    public PageInfo<Computer> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
        return computerService.selectAll(pageNum,pageSize);
    }

    @GetMapping("/{id}")
    public Computer selectById(@PathVariable("id") int id){
        return computerService.selectById(id);
    }

    @PutMapping("/")
    public void update(@RequestBody Computer computer){
        System.err.println(computer);
        computerService.updateById(computer);
    }


    @PostMapping("/")
    public void addComputer(@RequestBody Computer computer){
        System.err.println(computer);
        computerService.addComputer(computer);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") int id) {
        computerService.deleteById(id);
    }
    @DeleteMapping("/")
    public void deletes(@RequestBody int [] ids){
        for (int id : ids) {
            System.err.println(id);
        }
        computerService.deletes(ids);
    }

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐