【卷起来】VUE3.0教程-07-异步请求处理(springboot后端)

🌲 服务端接口准备

  • pom文件,引入mybatis/mybatis-plus相关依赖
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.1</version>
  </dependency>

  <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>2.3.1</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
  </dependency>
</dependencies>

  • application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/study

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis.mapper-locations=classpath*:mappers/*
mybatis.type-aliases-package=com.moxuan.vue_demo.entity
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

  • 启动类
package com.moxuan.vue_demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.moxuan.vue_demo.dao")
public class VueDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(VueDemoApplication.class, args);
    }

}
  • 工具类
package com.moxuan.vue_demo.util;

/**
 * 返回给客户端的状态码
 *
 * 封装状态码和消息的对应关系
 */
public enum ReturnCode {

    /*** 全局的returnCode,规定好后,任何人都不能变动这里面的内容  ***/
    SUCCESS("0000","操作成功"),
    BUSSINESS_EXCEPTION("1000","业务系统异常"),

    USER_NOT_LOGIN("8001","用户未登录"),
    ACCESS_FORBIDDEN("8002","无访问权限"),
    AUTHEN_FAILURE("8003","认证失败"),
    TOKEN_FORBIDDEN("8004","无访问口令,请登录后获取");

    /**
     * 状态码
     */
    private String code;
    /**
     * 返回的消息
     */
    private String msg;
    ReturnCode(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String code() {
        return this.code;
    }

    public String msg(){
        return this.msg;
    }
}

package com.moxuan.vue_demo.util;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Result {
    private String code;
    private String msg;
    private Object data;// 数据源

    /**
     * 当不需要携带data数据,只返回状态码和对应的消息时
     * @param returnCode
     * @return
     */
    public static Result sendResult(ReturnCode returnCode){
        Result result = new Result();
        result.setCode(returnCode.code());
        result.setMsg(returnCode.msg());
        return result;
    }

    /**
     * 当返回结果是,需要携带数据,调用这个方法
     * @param returnCode
     * @param data
     * @return
     */
    public static Result sendResult(ReturnCode returnCode,Object data) {
        Result result =  sendResult(returnCode);
        result.setData(data);
        return result;
    }

}
  • Dao接口
package com.moxuan.vue_demo.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.moxuan.vue_demo.entity.Hero;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface HeroMapper extends BaseMapper<Hero> {
}

  • service业务层
package com.moxuan.vue_demo.service;

import com.moxuan.vue_demo.dao.HeroMapper;
import com.moxuan.vue_demo.entity.Hero;
import com.moxuan.vue_demo.util.Result;
import com.moxuan.vue_demo.util.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HeroService {
    @Autowired
    private HeroMapper heroMapper;



    public Result getHeros() {
        List<Hero> heroList = heroMapper.selectList(null);
        return Result.sendResult(ReturnCode.SUCCESS,heroList);
    }

    public Result saveHero(Hero hero) {
        int count = heroMapper.insert(hero);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }

    public Result updateHeroById(Hero hero) {
        int count = heroMapper.updateById(hero);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }


    public Result deleteHero(int id) {
        int count = heroMapper.deleteById(id);
        if (count ==0){
            return Result.sendResult(ReturnCode.BUSSINESS_EXCEPTION);
        }
        return Result.sendResult(ReturnCode.SUCCESS);
    }
}
  • 控制层
package com.moxuan.vue_demo.controller;

import com.moxuan.vue_demo.service.HeroService;
import com.moxuan.vue_demo.entity.Hero;
import com.moxuan.vue_demo.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
//@RequestMapping("/api")
public class HeroController {
    @Autowired
    private HeroService service;
    @GetMapping("/hero")
    public Result getHeros(){
        log.info("查询所有的用户");
        return service.getHeros();
    }

    @PostMapping("/hero")
    public Result saveHero(Hero hero){
        return service.saveHero(hero);
    }

    @PutMapping("/hero")
    public Result updateHero(Hero hero){
        return service.updateHeroById(hero);
    }

    @DeleteMapping("/hero/{id}")
    public Result deleteHero(@PathVariable int id){
        return service.deleteHero(id);

    }
}

🌲 axios使用

🌿 axios 库下载

Axios 是一个基于promise的网络请求库,Axios的应用是需要单独安装的

npm  install --save axios

如图所示:

🌿 解决跨域问题

应用程序跨服务器访问时,经常可能出现跨域问题,这里我们先解决一下vue的跨域问题。我们找到项目的vite.config.js(vite的配置文件),添加如下代码:

server:{
  // 配置代理
  proxy:{
      // 配置代理请求前缀
      // 当vue发送localhost:5173/api/xxx请求时
      '/api': {
        // 实际上执行的是 http://localhost:8080/xxx
        target: 'http://localhost:8080/',
          changeOrigin: true,
          // 到达真实服务器地址时,去掉请求前缀/api
          // 比如前端发送请求http://localhost:5173/api/hero
          // 经过rewrite重写后会变成:http://localhost:8080/hero
          rewrite: (path) => path.replace(/^\/api/, '')
      }
  } 
}

🌿 get请求

使用axios发送get请求时,需要先在组件中导入axios

import axios from 'axios'

具体发送请求代码:

<script setup>
    import axios from 'axios'
    import {ref} from 'vue'
    const data = ref([])
    // get请求
    axios({
        method:'get',
        url:'/api/hero'  // 此处请求前需要加/api才能被代理识别
    }).then(res=>{
        console.log(res.data)
        // data.value = res.data.data;
    });
</script>

运行结果:

🌿 post请求

post请求参数需要额外处理,否则后端解析不到相关数据

  • 首先安装依赖
npm install --save querystring

  • 在组件中导入querystring
import qs from 'querystring'
  • 完整代码
<template>
    <button @click="addHero">添加数据</button>
</template>

<script setup>
    import axios from 'axios'
    import qs from 'querystring'
    import { computed } from 'vue';
   
    
    const addHero = computed(()=>{
        axios({
        method:'post',
        url:'/api/hero',
        data:qs.stringify({
            hname:"雪如意",
            sex:'女',
            job:"法师",
            level:12
        })
    }).then(res=>{
        console.log(res.data)
    });

    });
    
</script>

🌿 快捷方案

🍁 get请求
axios.get("/api/hero").then(res=>{
      console.log(res.data)
})
🍁 post请求
axios.post(
  "/api/hero",
  qs.stringify({
    hname:"马大哈",
    sex:'男',
    job:"法师",
    level:11
  })
).then(res=>{
  console.log(res.data)
})

🍁 put请求
axios.put(
  "/api/hero/",
  qs.stringify({
    id:1,
    hname:"雪如意",
    sex:'男'
  })

).then(res=>{
  console.log(res.data)
})

🍁 delete请求
axios.delete(
  "/api/hero/"+id.value

).then(res=>{
  console.log(res.data)
})

🍁 完整代码:

<template>
    
    <button @click="addHero">添加数据</button><br/>
    <button @click="getAllHeros">查询数据</button><br/>
    <input type="text" v-model="id"><button @click="updateHero">修改数据</button><br/>
    <hr/>
    <input type="text" v-model="id"><button @click="deleteHero">删除数据</button><br/>
</template>

<script setup>
    import axios from 'axios'
    import qs from 'querystring'
    import { computed,ref } from 'vue';

    const getAllHeros = computed(()=>{
        axios.get("/api/hero").then(res=>{
            console.log(res.data)
        })
    })
   
    
    const addHero = computed(()=>{
        axios.post(
            "/api/hero",
            qs.stringify({
                hname:"马大哈",
                sex:'男',
                job:"法师",
                level:11
                })
        ).then(res=>{
            console.log(res.data)
        })

    });

    const id = ref(0)
    const updateHero = computed(()=>{
        
        if(id.value==0){
            alert("请输入要修改数据的id")
        }else{
            axios.put(
                "/api/hero/",
                qs.stringify({
                    id:id.value,
                    hname:"雪如意",
                    sex:'男'
                })

            ).then(res=>{
                console.log(res.data)
            })
         }
        
    })

    const deleteHero = computed(()=>{
        axios.delete(
                "/api/hero/"+id.value
            
            ).then(res=>{
                console.log(res.data)
            })
    })
    
</script>

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 3.0 是一款流行的 JavaScript 框架,而 el-autocomplete 则是一款基于 Vue.js 的自动完成组件,用于输入框的自动补全功能。下面是使用 Vue 3.0 和 el-autocomplete 实现自动补全功能的简单示例: 首先,你需要在项目中安装 el-autocomplete 组件: ```bash npm install element-ui el-autocomplete -S ``` 然后,在你的 Vue 组件中引入 el-autocomplete 组件,并在模板中使用: ```html <template> <div> <el-autocomplete v-model="inputValue" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect" ></el-autocomplete> </div> </template> <script> import { ref } from 'vue'; import { fetchSearchResult } from '@/api'; export default { name: 'MyComponent', setup() { const inputValue = ref(''); const querySearchAsync = async (queryString, callback) => { const res = await fetchSearchResult(queryString); if (res.code === 200) { callback(res.data); } }; const handleSelect = (item) => { console.log(item); }; return { inputValue, querySearchAsync, handleSelect, }; }, }; </script> ``` 上面的代码中,我们使用了 Vue 3.0 的 Composition API,通过 `ref` 创建了一个响应式变量 `inputValue`,用于存储输入框的值。`querySearchAsync` 函数用于异步获取搜索结果,该函数会在用户每次输入时被调用。`handleSelect` 函数会在用户选择某个搜索结果时被调用。 这里的 `fetchSearchResult` 函数是一个异步函数,用于从后端获取搜索结果。你需要根据你的项目实际情况来实现该函数。 至此,我们已经完成了使用 Vue 3.0 和 el-autocomplete 实现自动补全功能的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听潮阁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值