Home > Web Front-end > Vue.js > body text

What is the usage of axios in vuejs

藏色散人
Release: 2023-01-13 00:45:39
Original
2620 people have browsed it

How to use axios in vuejs: 1. Install axios; 2. Reference axios on the main.js page; 3. Pass "created(){this.$axios({method:'post',url: 'api'...}" can be used.

What is the usage of axios in vuejs

The operating environment of this article: Windows 7 system, vue version 2.9.6, DELL G3 computer.

What is the usage of axios in vuejs?

Basic usage of axios in vue

1. First install axios:

What is the usage of axios in vuejs

1):npm install

2):npm install vue-axios --save

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

2. After successful installation, quote on the main.js page:

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

3 Finally start using the request:

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

Initiate multiple requests at the same time

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
Copy after login
创建一个实例
你可以创建一个拥有通用配置的axios实例

axios.creat([config])
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
Copy after login

Recommended learning: "vue tutorial"

The above is the detailed content of What is the usage of axios in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template