<p>一、npm 安装axios,文件根目录下安装,指令如下</p><p>npm install axios --save-dev</p><p>二、修改原型链,在main.js中引入axios</p><p>import axios from &#39;axios&#39;</p><p>接着将axios改写为Vue的原型属性,</p><p>Vue.prototype.$http=axios</p><p>这样之后就可在每个组件的methods中调用$http命令完成数据请求</p><p>三、在组件中使用</p><pre class="brush:js;toolbar:false"> methods:{ get(){ this.$http({ method:&#39;get&#39;, url:&#39;/url&#39;, data:{} }).then(function(res){ console.log(res) }).catch(function(err){ console.log(err) }) this.$http.get(&#39;/url&#39;).then(function(res){ console.log(res) }).catch(function(err){ console.log(err) }) } }</pre><p>有关axios的配置请参考如下文档,点击打开链接</p><p>下面给大家介绍下vue-cli配置axios的方法</p><p>1.</p><p>npm install axios --save</p><p>npm install @type/axios --save-dev(使用ts编写的需要此声明文件,升级的axios好像不需要了,已经自带)</p><p>3.</p><p>在src目录下添加axios.ts文件,内容:</p><pre class="brush:js;toolbar:false">importaxiosfrom&#39;axios&#39; import{Notification}from&#39;element-ui&#39; importstorefrom&#39;./store/index&#39; importbuildconffrom&#39;../config/build.rootpath.js&#39; axios.defaults.withCredentials=true; axios.defaults.baseURL=buildconf.serverUrl //axios.defaults.baseURL=&#39;http://gsblackwidow.chinacloudsites.cn/&#39; axios.interceptors.request.use(function(config){ //document.getElementById(&#39;g-loader&#39;).style.display=&#39;flex&#39; store.commit(&#39;requestModify&#39;,1) returnconfig; },function(error){ returnPromise.reject(error) }) axios.interceptors.response.use(function(response){ store.commit(&#39;requestModify&#39;,-1) //document.getElementById(&#39;g-loader&#39;).style.display=&#39;none&#39; returnresponse.data; },function(error){ store.commit(&#39;requestModify&#39;,-1) //document.getElementById(&#39;g-loader&#39;).style.display=&#39;none&#39; if(error.response.status===401){ Notification({ title:&#39;权限无效&#39;, message:&#39;您的用户信息已经失效,请重新登录&#39;, type:&#39;warning&#39;, offset:48 }); window.location.href=&#39;/#/login&#39; }else{ Notification({ title:&#39;请求错误&#39;, message:`${error.response.status}\n${error.config.url}`, type:&#39;error&#39;, offset:48, }) } returnPromise.reject(error) }) exportdefaultaxios</pre><p>4.</p><p>types文件夹中新建vue.d.ts文件,内容:</p><pre class="brush:js;toolbar:false"> import{AxiosStatic,AxiosInstance}from&#39;axios&#39; declaremodule&#39;vue/types/vue&#39;{ interfaceVue{ $axios:AxiosStatic; } }</pre><p>这样就可以在各个模块中通过this.$axios来使用axios了</p><p>其中axios中:</p><p>1. build.rootpath.js内容:</p><pre class="brush:js;toolbar:false">varpath=require(&#39;path&#39;) varrootpath=path.resolve(__dirname,&#39;../dist&#39;) module.exports=rootpath</pre><p>2. store是vuex的文件,所以要事先安装vuex</p><p>总结</p><p>以上所述是小编给大家介绍的vue-cli 引入、配置axios的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!</p>
T:0.049173s,M:248.07 KB
返回顶部 留言