vue axios summary article

1.npm --save and --save-dev What is the difference

When called to publish online production environment - to develop locally called development environment, - save that package will go to the line and on-line environment can be used to, for example you npm install a vue-router, the on-line environment also can be used to rely on, so you have to --save ~ vue-loader such as this component is only required when developing compilers like, the line is not required to, so we put the development of --save-dev in just fine ~ ~ ~ ~

2. Install vue axios

axios official document http://www.axios-js.com/

npm install

npm install --save axios vue-axios

main.js introduced

import axios from 'axios'
import VueAxios from 'vue-axios' 
Vue.use (VueAxios, axios)
### import references, Vue.use registered on the instance of vue

vue.use and Vue.prototype. $ xx difference

Three different ways tutorials vue components

Vue classic face questions: Vue.use and Vue.prototype $ xx blood it.?

index.vue used in the page

## 方法一
this.axios.get(api).then((response) => {
  console.log(response)
})
## Method Two
this.$http.get(api).then((response) => {
  console.log(response)
})
.Vue file ### in this represents the current vue, (response) => { } is used in the function to solve this wording es6 DIRECTION

3.vue deploy apache refresh the page 404

Add pseudo-static -> New File .htaccess file

 

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

4. axios concurrent requests

 

 this.axios.all([this.axios.get('/api/index/index'),this.axios({
      url:"/api/Address/index",
        params:{
          user_id:1
        }
      })]).then(res=>{
        console.log(res);
      })
##   / API to change the own address
 ## there are two writing get request, the second is written default get request, get request must pass parameters params: {}  
FIG disadvantages result is ## data words can take RES [ 0], RES [. 1]

this.axios.all([this.axios.get('/api/index/index'),this.axios({
      url:"/api/Address/index",
        params:{
          user_id:1
        }
      })]).then(this.axios.spread((res1,res2)=>{
              console.log(res1);
              console.log(res2);
      }))
## Use axios.spread
## data is now expanded state, following FIG.

 

5.axios Global Configuration

Provided the request timeout main.js

axios.defaults.timeout =  1000;

## 通过关键字 defaults 来设置
为什么要创建axios的实例呢?
当我们从axios模块中导入对象时, 使用的实例是默认的实例.
当给该实例设置一些默认配置时, 这些配置就被固定下来了.
但是后续开发中, 某些配置可能会不太一样.
比如某些请求需要使用特定的baseURL或者timeout或者content-Type等.
这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.

Common Configuration Item

Request address
url: '/user',
Request type
method: 'get',
Please root path
baseURL: 'http://www.mt.com/api' ,
The data processing requests before
transformRequest:[function(data){}],
After the data processing request
transformResponse: [function(data){}],
Custom request header
headers:{'x-Requested-With':'XMLHttpRequest'},
URL query object
params:{ id: 12 },
    
Query object serialization function
paramsSerializer: function(params){ }
request body
data: { key: 'aa'},
    
S timeout settings
timeout: 1000,
    
With or without cross-domain Token
withCredentials: false,
    
Custom request processing
adapter: function(resolve, reject, config){},
    
Authentication information
auth: { uname: '', pwd: '12'},
    
Json response data format / BLOB / Document / ArrayBuffer / text / Stream
responseType: 'json',

Axios create different instances where a project

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

axios Chinese Documents

6.axios package

A single package file request.js

import axios from 'axios'
Export function Request (config) {
   // 1. Create an instance of axios 
  const instance = axios.create ({
    baseURL: '/' fire ,
    timeout: 5000
  })
  return instance(config)
}
 ## where the return package out good example,

.vue file

// 导入
import { request } from "@/network/request";
 request({
        url: "/Address/index",
        params: {
          user_id: 1
        }
      }) .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
Examples of this package ### will have good. the then   the catch property, all on the line directly to get here
### confused. . The first argument here url request function +   params passed good example when config package, but the package did not see a good example of using this parameter, so I looked to find the source axios, see figure below.

View source code editor axios

 

7.axios interception

Request success / failure to intercept

In response success / failure to intercept

A total of four interceptor

A. To intercept each request

// 2.axios interceptor 
  // 2.1. Request interceptor role 
  instance.interceptors.request.use (config => {
    console.log(config);
    // 1. For example, some of the information in the config server does not meet the requirements 
// 2. For example, each time a network request, a request will want to display an icon in the interface // 3. Some network requests (such as log (token)), you must carry some special information return config

    
    ## results returned in the past must return it
  }, err => {
    // console.log(err);
  })

Two interception response

  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    // console.log(res);
    return res.data
      ### each arranged only return data in response to a successful
  }, err => {
    console.log(err);
  })

axios instance is an example of the beginning of the article package

Guess you like

Origin www.cnblogs.com/xfych/p/12028727.html