php 引入vue-cli,vue-cli引入、配置axios步骤详解

本文详细介绍了在 Vue CLI 项目中如何引入和配置 Axios,包括通过 npm 安装 Axios,修改原型链以全局使用,以及设置 Axios 的拦截器处理请求和响应。同时,还展示了在组件中调用 Axios 进行数据请求的方法,并提供了配置 Axios 的实际案例,涉及Vuex的集成和错误处理。此外,文章提及了如何在 TypeScript 项目中声明 Axios,确保类型检查。
摘要由CSDN通过智能技术生成

这次给大家带来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中文网其它相关文章!

推荐阅读:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值