Vue项目中使用axios如何进行参数拼接

本文详细介绍了在Vue项目中使用axios进行网络请求,包括get、post、put、delete等方法,重点讨论了参数拼接的不同方式,如字符串拼接、params属性传递和对象拼接,并提供了具体的代码示例。

一、Vue 中的网络请求
在Vue.js中发送网络请求本质还是Ajax,我们可以使用插件方便操作。

①vue-resource:Vue.js的插件,已经不维护,不推荐使用。
②axios:不是vue的插件,可以在任何地方使用,推荐使用。
      说明:axios既可以在浏览器端又可以在node.js中使用的发送http请求库,支持Promise语法,不支持jsonp请求(jsonp是解决跨域的)。如果遇到jsonp请求,可以使用插件jsonp实现。

二、axios的引入
① npm i axios
② script src =“cdn 加载”
③script src="./axios.main.js"
引入axios.main.js

三、常用网络请求方式
1、get
get请求方式将需要入参的数据作为 params 属性的值,最后整体作为参数传递。若没有请求参数,则可省略params属性。

data属性中封装的对象:
      //查询所有课程信息的参数对象-简单搜索
      queryCourseInfo: {
        name: "", //课程名称
        pageNum: 1, //当前的页数 。默认页码1
        pageSize: 10 //当前每页显示多少条数据。默认每页显示数量10
      },

上面接口发送请求以及参数拼接可以有以下方式:

A、字符串拼接方式:
    this.$axios
        .get(
          "/itoo-teach/teach/queryCourseInfoByName?name=" +
            this.queryCourseInfo.name +
            "&pageNum=" +
            this.queryCourseInfo.pageNum +
            "&pageSize=" +
            this.queryCourseInfo.pageSize
        )
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查询失败");
          }
          this.courseList = res.data.data.list;
          this.total = res.data.data.total;
        });
接收到的返回参数res包含的内容如下:

等同于下面的方式:
B、      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryCourseInfoByName?name=" +
          this.queryCourseInfo.name +
          "&pageNum=" +
          this.queryCourseInfo.pageNum +
          "&pageSize=" +
          this.queryCourseInfo.pageSize
      );
          if (res.code != "0000") {
            return this.$message.error("查询失败");
          }
          this.courseList = res.data.list;
          console.log(res);
          this.total = res.data.total;
变量res解构内容如下(将上方中的res.data进行解构,得到data属性中的内容):
B、通过params属性传递对象:
A、      this.$axios
        .get("/itoo-teach/teach/queryCourseInfoByName", {
          params: this.queryCourseInfo
        })
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查询失败");
          }
          this.courseList = res.data.data.list;
          console.log(res);
          this.total = res.data.data.total;
        });

    【params: this.queryCourseInfo 或者为:】
    this.$axios
        .get("/itoo-teach/teach/queryCourseInfoByName", {
          params: {
                name:this.queryCourseInfo.name,
                pageNum:this.queryCourseInfo.pageNum,
                pageSize:this.queryCourseInfo.pageSize,
            }
        }) 
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查询失败");
          }
          this.courseList = res.data.data.list;
          console.log(res);
          this.total = res.data.data.total;
        });

接收到的返回参数res包含内容如下:


B、      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryCourseInfoByName",
            {
              params: this.queryCourseInfo
            }
          );
          if (res.code != "0000") {
            return this.$message.error("查询失败");
          }
          this.courseList = res.data.list;
          console.log(res);
          this.total = res.data.total;


C、路径拼接方式:
接口:

上面接口中的请求参数name需要的类型是path,在url中的呈现的形式是:“接口/参数值”。

    async isExistByName() {
      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/isExistByName/(最后的“/”为url后面需要拼接的参数,将url与参数分隔。或者写成下面的形式)" + this.addCourseList.name(拼接的变量为 你需要传递的参数值)
      );

        const { data: res } = await this.$axios.get(
                "/itoo-teach/teach/isExistByName"+“/” + this.addCourseList.name
          );
      
      if (res.code != "0000") {
        alert("该课程名称已存在,请勿重复添加!");
        return;
      }
    },
D、无请求参数:
没有请求参数的get请求,直接写需要请求的ur即可:

//查询机构信息(学院信息)-lz-2020年6月18日18点39分
    async getInstitutionList() {
      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryAllInstitution" 
      ); //无请求参数,直接写url即可。
      if (res.code != "0000") {
        return this.$message.error("查询失败!");
      } else {
        this.institutionNameOptions = res.data;
      }
    },

2、post
A、Content-Type: application/json
json类型,headers里面设置’Content-Type’: ‘application/json; charset=utf-8’,这种形式的请求,我们只需要在axios的data属性中传递Object对象(参数作为请求体)即可。
//data属性中定义的对象变量:
      //表单信息添加/修改
      addCourseList: {
        // 学院id
        academyId: "",
        //课程代码
        code: "",
        //课程名称
        name: "",
        //课程类型
        courseType: "",
        //课程类别
        courseCategory: "",
        //课程性质
        courseNature: "",
        //所属学院
        institutionName: "",
        //学时
        classHour: "",
        //学分
        classPoint: "",
        //课程分数
        score: ""
      },

① 参数直接传递对象:
//添加信息
     const { data: res } = await this.$axios.post(
            "/itoo-teach/teach/create",
            this.addCourseList 【使用data属性中封装好的对象】
          );//body请求体  携带参数数据
          if (res.code != "0000") {
            return this.$message.error("提交课程信息失败!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });

② 通过data属性传递对象:
    // 请求体 data属性中携带参数对象
     const { data: res } = await this.$axios.post(
            "/itoo-teach/course/create",
            {
              data: { courseModel: this.addCourseList }
            }
          );// courseModel见接口需要的实体参数,保持一致。

headers请求体中包含的内容如下:
B、Content-Type: multipart/form-data
form-data类型,headers里面设置’Content-Type’: ‘multipart/form-data’,使用data属性直接传递Object对象即可。

① 文件上传
接口:

实现文件的上传:使用的是Element ui组件库中的upload组件

         <el-upload
          :action="actionUrl"
          ......【其余配置项略...】
        </el-upload>
data 中配置地址:
actionUrl: process.env.VUE_APP_Back + "itoo-teach/course/importCourse", //上传文件url 
//方式为post请求。使用组件上传,组件中已经为我们封装好了请求体部分--默认的参数是file,
//上方接口中的请求参数为file才可以,否则前端传递的参数是file,
//后端参数如果不是file(比如是mf),后端参数 mf 与 前端参数 file 不对应,则文件将传不过去。

headers请求体中包含的内容如下:
C、Content-Type: application/x-www-form-urlencoded。
目前这种情况在开发中还没有遇到过,所以下方图片并不为亲测,而是来源于网络。如果后面的开发中遇到这种情况,再进行更新…

3、put
put请求与上面的post请求中json(上面的2-A情况)请求格式类似。
① 参数直接传递对象:
const { data: res } = await this.$axios.put(
            "/itoo-teach/teach/modify",
            this.addCourseList
          );//请求参数封装在body请求体里
          if (res.code != "0000") {
            return this.$message.error("修改课程信息失败!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });
    },

② 通过data属性传递对象:
const { data: res } = await this.$axios.put(
            "/itoo-teach/teach/modify",
               {
              data: { courseModel: this.addCourseList }
             }
          );//请求参数封装在body请求体里
          if (res.code != "0000") {
            return this.$message.error("修改课程信息失败!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });
    },

4、delete
① 服务端将参数作为java对象来封装接收:
delete请求方式:(1)如果服务端将参数作为java对象来封装接收,将需要入参的数据作为 data 属性的值,最后整体作为参数传递;

② 服务端将参数作为url参数来接收:
delete请求方式:(2)如果服务端将参数作为url参数来接受,则请求的url为:www.demo/url?a=1&b=2形式,使用patams传递参数。
【***使用data还是params属性,看url地址是否有参数拼接。或者看接口,如果参数是body的形式,则使用data属性传递对象】
接口:


//根据所选课程ids,提交要删除的课程-lz-2020年6月11日16点40分
    async submitDeleteCourse() {
      const { data: res } = await this.$axios.delete(
        "/itoo-teach/teach/deleteByIds",
        {
          data: this.ids
        }
      );//delete需要data属性携带参数,body请求实体
      console.log("批量删除状态码为:" + res.code);
      if (res.code != "0000") {
        return this.$message.error("删除课程信息失败!");
      }
      this.getCourseList();
    },

四、说明:发送请求时使用function/箭头函数
如果在vue中使用axios发送请求,你在.then/.catch的回调函数中使用了箭头函数,那么this指向当前的组件实例。如果回调函数使用的是function函数,那么this指向undefined…
使用function函数时,vue中data中的数据无法通过this直接引用,需要做如下处理:var _this(vm)=this,先保存一下当前的this,即作用域为全局对象,否则this在function函数中指向当前对象,这样的话,在this处(this.$emit…)会发生错误 undefined.

或者写成箭头函数的形式:

上面两种方式都可以成功发送请求,不过,使用箭头函数不支持async函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值