国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue-cli 引入、配置axios的方法

2024-05-06 15:34:29
字體:
來源:轉載
供稿:網友

一、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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 安达市| 庄河市| 邓州市| 绵阳市| 镇江市| 栾川县| 新巴尔虎右旗| 怀安县| 怀宁县| 衢州市| 新竹县| 贵南县| 台中县| 渝北区| 烟台市| 东宁县| 油尖旺区| 长阳| 舒兰市| 区。| 吉安县| 斗六市| 黔东| 合水县| 句容市| 广昌县| 洛阳市| 同江市| 新竹市| 平南县| 桂东县| 丰台区| 札达县| 苍溪县| 运城市| 犍为县| 台东县| 恭城| 道真| 綦江县| 奉化市|