Vue-cli中axios基础用法

**

Vue-cli中axios基础用法

**

在使用axios时
首先安装axios

1:npm install

2:npm install vue-axios --save

3:npm install qs.js --save  //它的作用是能把json格式的直接转成data所需的格式

安装成功后
在VUE中main.js中加入这些代码

import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'

Vue.prototype.$axios = axios    //全局注册,使用方法为:this.$axios
Vue.prototype.qs = qs           //全局注册,使用方法为:this.qs

这是就可以再页面中使用axios

<script>
    export default{
        data(){
            return{
                username:'用户名',
          password:'密码',
            }
        },
        created(){
        //POST请求
            this.$axios({
                method:'POST',
                url:'api',
                data:this.qs.stringify({    //这里是发送给后台的数据
                      username:this.username,
                      password:this.password,
                })
            }).then((response) =>{          //这里使用了ES6的语法
                console.log(response)       //请求成功返回的数据
            }).catch((error) =>{
                console.log(error)       //请求失败返回的数据
            })
         //GET请求
          this.$axios({
                method:'GET',
                url:'api',
                params:{    //这里是发送给后台的数据
                      username:this.username,
                      password:this.password,
                }
            }).then((response) =>{          //这里使用了ES6的语法
                console.log(response)       //请求成功返回的数据
            }).catch((error) =>{
                console.log(error)       //请求失败返回的数据
            })
        }
    }
</script>

本文介绍的是axios的基本用法,详细看官方文档https://github.com/axios/axios

发布了3 篇原创文章 · 获赞 4 · 访问量 172

猜你喜欢

转载自blog.csdn.net/HelloWorld187/article/details/102910936