当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Vue中使用axios进行前后端的数据传输(附详细代码)

Vue中使用axios进行前后端的数据传输(附详细代码)

2020年08月01日  | 移动技术网IT编程  | 我要评论
Vue界面在前后端交互的过程中使用的是AJAX的方式来进行的数据交互,我们一般来说使用较多的是Vue-resource 以及 axios 这俩个组件来实现Vue的前后端的交互。但是在Vue1.0中官方推荐使用vue-resource,在Vue2.0的时候,官方推荐使用axios。并且在之后对Vue-resource不再进行维护更新。所以今天我就来说一说axios的使用。安装组件npm install axios --save然后在main.js文件中引入,axios不能使用use。import V

Vue界面在前后端交互的过程中使用的是AJAX的方式来进行的数据交互,我们一般来说使用较多的是Vue-resource 以及 axios 这俩个组件来实现Vue的前后端的交互。但是在Vue1.0中官方推荐使用vue-resource,在Vue2.0的时候,官方推荐使用axios。并且在之后对Vue-resource不再进行维护更新。所以今天我就来说一说axios的使用。

安装组件

npm install axios --save

然后在main.js文件中引入,axios不能使用use。

import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;

get请求

不带参数

this.$axios
        .get("http://localhost:8080/api/coffee/selectAllCoffee")
        .then(res => {
          console.log(res);
        });

带参数

this.$axios
        .get("http://localhost:8080/api/coffee/search", {
          params: {
            name: this.name
          }
        })
        .then(function(res) {
          console.log(res);     
        })
        .catch(resp => {
          console.log("请求失败:" + resp.status + "," + resp.statusText);
        });

Post请求

this.$axios.post("http://localhost:8080/api/machine/insertMachine",{
                machineId: that.form.machineId,
                coffeemachine: that.form.coffeemachine,
                machineKinds: that.form.machineKinds,
                machinePrice: that.form.machinePrice,
                state: that.radio,
                note: that.form.note,
                menuId:that.form.menuId
            }).then(res=>{
               console.log(res);
            })

post请求相较于get请求会相对复杂一点,他可能会存在数据格式不对的情况, 这时候就需要使用 qs 模块对 data 进行格式化。

1、首先安装qs

npm install qs

import qs from 'qs'

Vue.prototype.$qs=qs

2、使用qs对数据进行格式化

let data={
        coffeeId: that.form.coffeeId,
        coffeeName: that.form.coffeeName,
        coffeeKinds: that.form.coffeeKinds,
        coffeeDiscount: that.form.coffeeDiscount,
        newPrice: that.form.newPrice,
        oldPrice: that.form.oldPrice,
        coffeeImage:that.form.coffeeImage
      }
      this.$axios
        .post("http://localhost:8080/api/coffee/updateCoffee",qs.stringify(data),{
          headers: {
            'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
          }
        }
        )
        .then(res => {
          console.log(res);
        });

本文地址:https://blog.csdn.net/monkey_wei/article/details/108116424

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网