如何使用vue-cli引入、配置axios
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用vue-cli引入、配置axios,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2590字,纯文字阅读大概需要4分钟。
内容图文
![如何使用vue-cli引入、配置axios](/upload/InfoBanner/zyjiaocheng/289/b35e5fd10d18446e98ead2390c73c527.jpg)
一、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
相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
推荐阅读:
如何使用vux-ui自定义表单验证
Angular路由内路由守卫该如何使用
以上就是如何使用vue-cli引入、配置axios的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的如何使用vue-cli引入、配置axios全部内容,希望文章能够帮你解决如何使用vue-cli引入、配置axios所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。