首頁  >  文章  >  web前端  >  如何使用vue-cli引入、設定axios

如何使用vue-cli引入、設定axios

php中世界最好的语言
php中世界最好的语言原創
2018-05-31 09:37:431217瀏覽

這次帶給大家如何使用vue-cli引入、設定axios,使用vue-cli引入、設定axios的注意事項有哪些,以下就是實戰案例,一起來看一下。

一、npm 安裝axios,檔案根目錄下安裝,指令如下

npm install axios --save-dev 

二、修改原型鏈,在main.js中引入axios

import axios from 'axios' 

接著將axios改寫為Vue的原型屬性,

Vue.prototype.$http=axios 

這樣之後就可在每個元件的methods中呼叫$http指令完成資料請求

三、在元件中使用

methods: { 
   get(){ 
    this.$http({ 
     method:'get', 
     url:'/url', 
     data:{} 
    }).then(function(res){ 
     console.log(res) 
    }).catch(function(err){ 
     console.log(err) 
    }) 
     
    this.$http.get('/url').then(function(res){ 
     console.log(res) 
    }).catch(function(err){ 
     console.log(err) 
    }) 
   }    
}

有關axios的配置請參考如下文檔,點擊打開鏈接

#下面給大家介紹下vue-cli配置axios的方法

##1.

npm install axios --save

#2.

npm install @type/axios --save-dev(使用ts编写的需要此声明文件,升级的axios好像不需要了,已经自带)
3.

在src目錄下新增axios.ts文件,內容:

import axios from 'axios'
import {Notification} from 'element-ui'
import store from './store/index'
import buildconf from '../config/build.rootpath.js'
axios.defaults.withCredentials = true;
axios.defaults.baseURL = buildconf.serverUrl
// axios.defaults.baseURL = 'http://gsblackwidow.chinacloudsites.cn/'
axios.interceptors.request.use(function(config) {
 // document.getElementById('g-loader').style.display = 'flex'
 store.commit('requestModify', 1)
 return config;
}, function(error){
 return Promise.reject(error)
})
axios.interceptors.response.use(function(response){
 store.commit('requestModify', -1)
 // document.getElementById('g-loader').style.display = 'none' 
 return response.data;
}, function(error){
 store.commit('requestModify', -1) 
 // document.getElementById('g-loader').style.display = 'none'  
 if(error.response.status === 401){
  Notification({
   title: '权限无效',
   message: '您的用户信息已经失效, 请重新登录',
   type: 'warning',
   offset: 48
  });
  window.location.href = '/#/login'
 }else{
  Notification({
   title: '请求错误',
   message: `${error.response.status} \n ${error.config.url}`,
   type: 'error',
   offset: 48,
  })
 }
 return Promise.reject(error)
})
export default axios
4.

types資料夾中新建vue.d.ts文件,內容:

import {AxiosStatic, AxiosInstance } from 'axios'
declare module 'vue/types/vue' {
 interface Vue {
  $axios: AxiosStatic;
 }
}
這樣就可以在各個模組中透過this.$axios來使用axios了

其中axios中:

#1. build.rootpath.js內容:

var path = require('path')
var rootpath = path.resolve(dirname, '../dist')
module.exports = rootpath
2. store是vuex的文件,所以要事先安裝vuex

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

如何使用vux-ui自訂表單驗證

#Angular路由內路由守衛該如何使用
#

以上是如何使用vue-cli引入、設定axios的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn