問題
相信很多人在用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.創(chuàng)建如下圖中的文件夾和文件

2.在 Loading.vue 中定義一個組件
<template>
? ? ? ? <div class="loading-box">
? ? ? ? ? ?loading...
????????</div>
</template>
3.在 jndex.js 中 引入 Loading.vue ,并導出
...// 引入組件...
...importLoadingComponentfrom'./loading.vue'...
...// 定義 Loading 對象...
...constLoading={...
// install 是默認的方法。當外界在 use 這個組件的時候,就會調用本身的 install 方法,同時傳一個 Vue 這個類的參數(shù)。
...install:function(Vue){...
? ? ? ? ?... Vue.component('Loading',LoadingComponent)..
... }...
...}...
...// 導出...
...exportdefaultLoading...
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里面寫入定義好的組件標簽 ...<loading></loading>...
...<template>...
...<div id="app">...
...<h1>vue-loading</h1>...
...<loading></loading>...
...</div>
...</template>...
6.看到這兒大家應該就明白了吧,用?axios時,之所以不需要用?Vue.use(axios),就能直接使用,是因為開發(fā)者在封裝?axios?時,沒有寫?install?這一步。至于為啥沒寫,那就不得而知了。