zoukankan      html  css  js  c++  java
  • Vue 中使用axios 处理请求数据

    安装就不过多讲解了,请移步至 axios 学习文档

    仔细看看文档,就知道axios 是一个基于 promise 的 HTTP 库,axios并没有install 方法,所以是不能使用vue.use()方法的。☞查看 Vue 插件
    那么难道我们要在每个文件都要来引用一次axios吗?多繁琐!!!解决方法有很多种:

    1. 结合 vue-axios使用
    2. axios添加到 Vue 的原型属性
    3. 结合 Vuex的action

    1.结合 vue-axios使用

    vue-axios,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了,首先在主入口文件main.js中引用:

    import axios from axios'
    import Vueaxios from vue-axios
    
    Vue . use ( Vueaxios , axios )
    

    之后就可以使用了,在组件文件中的methods里去使用了:

    getNewsList(){
      this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })
    }
    

    2.axios 改写为 Vue 的原型属性(不推荐这样用)

    首先在主入口文件main.js中引用,之后挂在vue的原型链上:

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

    在组件中使用:

    this.$axios.get('api/getNewsList')
      .then(response)=>{
        this.newsList=response.data.data;
      }).catch(response)=>{
        console.log(response);
      })
    
    

    3. 结合 Vuex的action

    在vuex的仓库文件store.js中引用,使用action添加方法

    import Vue from 'Vue'
    import Vuex from 'vuex'
    
    import axios from 'axios'
    
    Vue.use(Vuex)
    const store = new Vuex.Store({
      // 定义状态
      state: {
        user: {
          name: 'xiaoming'
        }
      },
      actions: {
        // 封装一个 ajax 方法
        login (context) {
          axios({
            method: 'post',
            url: '/user',
            data: context.state.user
          })
        }
      }
    })
    
    export default store
    

    axios 处理get 、 post 请求

    created发送请求

    // created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
    created(){
        axios.get('api/getData.php',{       // 还可以直接把参数拼接在url后边
            params:{
                title:'眼镜'
            }
        }).then(function(res){
            this.goodsList = res.data;
        }).catch(function (error) {
            console.log(error);
        });
    }
    
    

    在组件中发送请求的时候,需要使用 this.$store.dispatch

    mtehods:{
      submitForm (){
        this.$store.dispatch('login')
      }
    }
    
    
    

    发送POST请求

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }).then(function (response) {
        console.log(response);
    }).catch(function (error) {
        console.log(error);
    });
    
    // 注意: 如果发送请求时,发现传递的参数是对象,那么可用如下方式传参数
    // var params = new URLSearchParams();
    // params.append('title', '眼镜');
    // params.append('id',1);
    // axios.post('/user', params)
    //      .then(function(res){})
    //      .catch(function(error){});
    

    请求拦截器和响应拦截器

    //请求拦截器
    axios.interceptors.request.use(
      function (config) {
          // 在发送请求之前做些什么
          return config;
      },
      function (error) {
          // 对请求错误做些什么
          return Promise.reject(error);
      }
    );
    
    //响应拦截器
    axios.interceptors.response.use(
      function (config) {
          // 对响应数据做点什么
          return config;
      },
      function (error) {
          // 对响应错误做点什么
          return Promise.reject(error);
      }
    );
    
    

    Vue中axios在发送POST请求时,参数的处理

    post请求参数的两种格式:

    form-data:?name=iwen&age=10
    x-www-form-urlencoded:{name:'iwen',age:20}
    

    注意:axios接收的post请求参数的格式是form-data格式,所以需要使用插件“qs”,将请求参数转换为form-data格式。如下:

    1. 下载安装第三方模块 qs -> npm install qs --save-dev
    2. 处理方式
    
    // 第一种: 在vue组件中,直接在发送的时候,对数据进行qs.stringify处理
    // 缺点: 如果项目大,有大量的请求需要发送,那么一个一个加会很麻烦
    axios.post("/checkLogin.php", qs.stringify({
      name:'tom',
      pwd:12345
    }));
    
    // 第二种:在 main.js 中,使用axios.create创建一个新的axios实例,统一对数据进行处理, 同时也要借助qs模块
    const Axios = axios.create({
      baseURL: '/api',
      transformRequest: [function (data) {
        const d = qs.stringify(data)
        return d;
      }]
    })
    //在vue组件中就可以直接传json了
    Axios.post("/checkLogin.php", {
      name:'tom',
      pwd:12345
    });
    
    // 第三种:在main.js中,使用axios拦截器处理数据,实例应用:在post请求的时候需要将请求参数进行转换,这个操作可以在拦截器中处理,这样在单独的组件中,请求参数就不需要处理了。如下:
    import qs from 'qs'
    
    Axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      console.log(config)
      if(config.method === 'post'){
      //将请求参数进行转换,这里是全局配置post请求参数
        config.data = qs.stringify(config.data)
      }
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    
    //在vue组件中就可以直接传json了
    Axios.post("/checkLogin.php", {
      name:'tom',
      pwd:12345
    });
    
    
  • 相关阅读:
    css变量
    es6的this指向
    Java面试题(包装类)
    moment笔记
    Class
    CSS斜切角
    Element.getBoundingClientRect()
    Do not mutate vuex store state outside mutation handlers.
    antd不想写那么多option怎么办
    解析URL参数
  • 原文地址:https://www.cnblogs.com/jiaoshou/p/13524655.html
Copyright © 2011-2022 走看看