問(wèn)題
相信很多人在用Vue使用別人的組件時(shí),會(huì)用到 Vue.use() 。例如:Vue.use(VueRouter)蒿囤、Vue.use(MintUI)。但是用 axios時(shí)崇决,就不需要用 Vue.use(axios)材诽,就能直接使用。那這是為什么吶嗽桩?
答案
因?yàn)?axios 沒(méi)有 install岳守。
什么意思呢凄敢?接下來(lái)我們自定義一個(gè)需要 Vue.use() 的組件碌冶,也就是有 install 的組件,看完之后就明白了涝缝。
定義組件
生成模版? vue init webpack-simple custom-global-component
custom-global-component 為新建的文件夾名稱
然后一路回車
cd custom-global-component 進(jìn)入該文件夾
npm install 安裝本次需要的模塊
npm run dev 運(yùn)行項(xiàng)目
如果能正常打開(kāi)扑庞,進(jìn)行下一步
1.在 Loading.vue 中定義一個(gè)組件
<template>
? ? <div class="loading-box">
? ? ? ? Loading...
? ? </div>
</template>
2.在 jndex.js 中 引入 Loading.vue ,并導(dǎo)出
// 引入組件
import LoadingComponent from './loading.vue'
// 定義 Loading 對(duì)象
const Loading={
? ? // install 是默認(rèn)的方法拒逮。當(dāng)外界在 use 這個(gè)組件的時(shí)候罐氨,就會(huì)調(diào)用本身的 install 方法,同時(shí)傳一個(gè) Vue 這個(gè)類的參數(shù)滩援。
? ? install:function(Vue){
? ? ? ? Vue.component('Loading',LoadingComponent)
? ? }
}
// 導(dǎo)出
export default Loading
3.在 main.js 中引入 loading 文件下的 index/中'./components/loading/index' 的 /index 可以不寫栅隐,webpack會(huì)自動(dòng)找到并加載 index 。如果是其他的名字就需要寫上玩徊。
import Loading from './components/loading/index'
// 這時(shí)需要 use(Loading)租悄,如果不寫 Vue.use()的話,瀏覽器會(huì)報(bào)錯(cuò)恩袱,大家可以試一下
Vue.use(Loading)
4.在App.vue里面寫入定義好的組件標(biāo)簽 <Loading></Loading>
<template>
? <div id="app">
? ? <h1>vue-loading</h1>
? ? <Loading></Loading>
? </div>
</template>
5.看到這兒大家應(yīng)該就明白了吧泣棋,用 axios時(shí),之所以不需要用 Vue.use(axios)畔塔,就能直接使用潭辈,是因?yàn)殚_(kāi)發(fā)者在封裝 axios 時(shí)鸯屿,沒(méi)有寫 install 這一步。至于為啥沒(méi)寫把敢,那就不得而知了寄摆。