2020-05-14 Vue mounted()中使用axios的一个小坑

656 阅读1分钟

main.js中:

import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
require("./mock.js");
import axios from "axios";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

axios.defaults.baseURL = "http://mockjs.com/api"; // 设置默认请求的url
Vue.prototype.$axios = axios;

就引入了一下axios,然后设置默认请求url并挂载到Vue上

组件中:

export default {
  data: function() {
    return {
      a: 111
    };
  },
  methods: {
    async getInitData() {
      console.log(this.$axios);
      let res = await this.$axios.get("/posts");
      console.log(res);
    }
  },
  mounted() {
    this.getInitData();
  }
};

此时问题出现了,死活获取不到 this.$axios,刚开始还以为async的函数 this 指向有问题,可是 this.a 又可以获取的到。

突然想起写在 Vue 中用 echarts 的案例,改了一下:

mounted() {
    this.$nextTick(function() {
      this.getInitData();
    });
  }

放入$nextTick中就可以获取到了

问了一下大佬,原来是我脑残了,main.js里应该把挂原型的操作放在渲染之前:

Vue.config.productionTip = false;
axios.defaults.baseURL = "http://mockjs.com/api"; // 设置默认请求的url
Vue.prototype.$axios = axios;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");