Vue使用vue-axios插件

一、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**:然后直接在需要的地方进行请求即可:
    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…

猜你喜欢

转载自blog.csdn.net/qq_42363090/article/details/89007711