一、vue-axios插件的安装
使用 npm
$ cnpm install axios
二、vue-axios插件的引用
出于页面的优雅考虑,使用vue2.0 vue-cli脚手架的代码风格去实现。
1、创建引用文件:
用ide打开项目文件,在src目录下创建文件夹axios,后在文件夹内创建index.js。如图:
2.编写引用的相关代码:
step1: axios下的index.js:
/引入Vue框架/
import Vue from 'vue';
/*引入资源请求插件*/
import axios from 'axios';
/*使用axios插件*/
Vue.prototype.$axios = axios;
export default({
});
step2: src下的main.js,代码引入已经引用好的axios文件
import Vue from 'vue';
import App from './App';
import router from './router';
import resource from './resource';
import axios from './axios';//通过import引入
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({ el: '#app', router, resource, axios,//通过import引入,然后在这里调用 components: { App }, template: '<App/>' });
step3: App.vue页面的发起的数据请求,案例是mock,调用本地的data.json。
export default {
name: 'App', data() {
return { itemList: [], }
}, mounted()
{ this.getAjax(); },
methods:{ getAjax:function ()
{ this.$axios.get('api/seller') .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); }); }, } }
tip: 此处的‘api、seller’为本地自己配置的data.json文件的数据,可以直接替换成url路径。成功调用axios,服务器会返回data数据包,如图,在谷歌按F12(开发者模式下):
只要实现该效果即可。如果问题请继续往下看__
三、使用vue-axios插件常见问题(踩坑)
看似很简单,但是经常会遇到一些奇奇怪怪的问题。
3.1 vue用axios时报错:Cannot read property ‘protocol’ of undefined!
遇到这种情况的小伙伴,主要是陷入了一个误区。 axios 是一个vue插件这话没毛病,但是,重点来了!!!axios使用方法跟vue-router以及vue-resource的调用方式不同,不能使用Vue.use(axios)
而是:
/*使用axios插件*/
Vue.prototype.$axios = axios;
可以参照上方step2的格式书写。
持续踩坑ing…
作者:吴维炜
来源:CSDN
原文:https://blog.csdn.net/qq_38209578/article/details/79225698
版权声明:本文为博主原创文章,转载请附上博文链接!
作者:吴维炜
来源:CSDN
原文:https://blog.csdn.net/qq_38209578/article/details/79225698
版权声明:本文为博主原创文章,转载请附上博文链接!