VUE使用axios

    科技2024-06-26  72

    1,npm一下

    npm install vue-axios --save npm install qs.js --save  //这一步可以先忽略,它的作用是能把json格式的直接转成data所需的格式

    2.main.js中

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

    3.使用

    <script> export default{ data(){ return{ userId:666,           token:'', } }, created(){ this.$axios({ method:'post', url:'api', data:this.qs.stringify({ //这里是发送给后台的数据 userId:this.userId, token:this.token, }) }).then((response) =>{ //这里使用了ES6的语法 console.log(response) //请求成功返回的数据 }).catch((error) => console.log(error) //请求失败返回的数据 }) } } </script>
    Processed: 0.023, SQL: 8