遇到的問題
相信很多人在用Vue使用別人的組件時柄冲,會用到 Vue.use() 。例如:Vue.use(VueRouter)刊头、Vue.use(MintUI)骄噪。但是用 axios時刻盐,就不需要用 Vue.use(axios)掏膏,就能直接使用。那這是為什么吶敦锌?
答案
axios是第三方組件馒疹,不是vue自帶組件,所以不能用Vue.use(axios)供屉。
定義組件
生成模版 vue init webpack-simple custom-global-component
custom-global-component 為新建的文件夾名稱
然后一路回車
cd custom-global-component 進入該文件夾
npm install 安裝本次需要的模塊
npm run dev 運行項目
如果能正常打開行冰,進行下一步
這是當前項目目錄:
文件夾和文件
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 這個組件的時候悼做,就會調(diào)用本身的 install 方法,同時傳一個 Vue 這個類的參數(shù)哗魂。
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里面寫入定義好的組件標簽 <Loading></Loading>
<template>
<div id="app">
<h1>vue-loading</h1>
<Loading></Loading>
</div>
</template>
6.看到這兒大家應該就明白了吧葫男,用 axios時,之所以不需要用 Vue.use(axios)崔列,就能直接使用梢褐,是因為在創(chuàng)建項目就的時候,我們就引入了axios,定義了它全局或者局部使用赵讯,所以可以直接使用盈咳。