VueAxios, axios 引入, 爲什麼需要 vue-axios?

引入 Vue

在 resources/js/app.js 文件中, 以下兩種寫法都可以引入Vue, 使用其中一種即可:

window.Vue = require('vue'); 
import Vue from 'vue'; 

引入 axios

錯誤示範

這種寫法不支持, 因爲 axios 是第三方庫, 不是vue的插件

/** 錯誤寫法
 * import axios from 'axios';
 * Vue.use(axios) 
 */

當作插件文檔引入

按照Vue的插件文檔來寫, 更符合 Vue 整體生態環境, vue-axios 是將 axios 集成到 Vue.js 的小包裝器,可以像插件一樣進行安裝:

import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);

前端用法:

this.axios.get(api).then((response)=>{
    console.log(response.data);
})

Vue.axios.get(api).then((response)=>{
    console.log(response.data);
}); 

this.$http.get(api).then((response)=>{
    console.log(response.data);
})

可以瞭解下 vue-axios 的源碼, $http, axios 是 axios 在 Vue.prototype 原型中的綁定名稱,.

(function () {

/**
 * Install plugin
 * @param Vue
 * @param axios
 */

function plugin(Vue, axios) {

  if (plugin.installed) {
    return
  }
  plugin.installed = true

  if (!axios) {
    console.error('You have to install axios')
    return
  }

  Vue.axios = axios

  Object.defineProperties(Vue.prototype, {

    axios: {
      get() {
        return axios
      }
    },

    $http: {
      get() {
        return axios
      }
    }

  })
}

if (typeof exports == "object") {
  module.exports = plugin
} else if (typeof define == "function" && define.amd) {
  define([], function(){ return plugin })
} else if (window.Vue && window.axios) {
  Vue.use(plugin, window.axios)
}

})();

原型綁定引入

在原型上進行綁定, 直接寫原型鏈, 註冊一個$http,和項目其他成員協作的時候就必須註明你註冊的變量名稱,而使用vue-axios大家就沒有歧義, 因此此用法不推薦.

import axios from 'axios';
Vue.prototype.$http = axios; 
// 也可以寫成  Vue.prototype.$axios = axios, 調用, this.$axios;

在模版引擎中用法是:

// 爲給定 ID 的 user 創建請求: 
this.$http.get('user?id=12345')
    .then(function(response){
		console.log(response);
	})
    .catch(function(error){
		console.log(error);
    }) 

或者這麼寫

this.$http.get('/user', {
		params: { id: 12345 }
	})
	.then(function(response){
		console.log(response);
	})
	.catch(function(error){
		console.log(error);
	})

實際引入

Laravel 項目中由於 npm install 自動安裝了 axios, 並在 resources/js/bootstrap.js 中自動掛載到 window:

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

實際, 只需要在 resources/js/app.js 文件中把 axios 註冊到 Vue 原型中即可, 不需要再次引入.

require('./bootstrap');
window.Vue = require('vue');
Vue.prototype.axios = window.axios;

前端中使用:

this.axios.get(api).then((response)=>{
	return response.data;
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章