關於Vue.use()詳解
相信很多人在用Vue使用別人的元件時,會用到 Vue.use() 。例如:Vue.use(VueRouter)、Vue.use(MintUI)。但是用 axios時,就不需要用 Vue.use(axios),就能直接使用。那這是為什麼吶?
答案
因為 axios 沒有 install。
什麼意思呢?接下來我們自定義一個需要 Vue.use() 的元件,也就是有 install 的元件,看完之後就明白了。
定義元件
生成模版 vue init webpack-simple custom-global-component custom-global-component 為新建的資料夾名稱 然後一路回車 cd custom-global-component 進入該資料夾 npm install 安裝本次需要的模組 npm run dev 執行專案 如果能正常開啟,進行下一步
這是當前專案目錄:

1.建立如下圖中的資料夾和檔案

2.在 Loading.vue 中定義一個元件
<template> <div class="loading-box"> Loading... </div> </template> 複製程式碼
3.在 index.js 中 引入 Loading.vue ,並匯出
// 引入元件 import LoadingComponent from './loading.vue' // 定義 Loading 物件 const Loading={ // install 是預設的方法。當外界在 use 這個元件的時候,就會呼叫本身的 install 方法,同時傳一個 Vue 這個類的引數。 install:function(Vue){ Vue.component('Loading',LoadingComponent) } } // 匯出 export default Loading 複製程式碼
4.在 main.js 中引入 loading 檔案下的 index
// 其中'./components/loading/index' 的 /index 可以不寫,webpack會自動找到並載入 index 。如果是其他的名字就需要寫上。 import Loading from './components/loading/index' // 這時需要 use(Loading),如果不寫 Vue.use()的話,瀏覽器會報錯,大家可以試一下 Vue.use(Loading) 複製程式碼
5.在App.vue裡面寫入定義好的元件標籤
<template> <div id="app"> <h1>vue-loading</h1> <Loading></Loading> </div> </template> 複製程式碼
6.看到這兒大家應該就明白了吧,用 axios時,之所以不需要用 Vue.use(axios),就能直接使用,是因為開發者在封裝 axios 時,沒有寫 install 這一步。至於為啥沒寫,那就不得而知了。