Vue.use(ElementUI) 做了什么?
本文轉載自微信公眾號“素燕”(gh_a97f4df5b7b9)。
在使用 ElementUI 組件的時候,通常我們會這么寫:
- import ElementUI from 'element-ui';
- Vue.use(ElementUI);
這樣寫完后,在我們自定義的組件中既可以直接使用:
- <template>
- <div>
- <el-button type="primary">我是素燕</el-button>
- </div>
- </template>
通過本文我們來分析下它是如何實現的。
Vue 提供了一種插件機制,可以給 Vue 擴充一些屬性,其實這個插件比較"可笑",什么也沒做,不信看下源碼:
Vue 內部只是幫你判斷了下有沒有重復注冊,并調用了你傳給它的函數,其實我自已也可以調用,反而饒了一圈,可能框架設計有自己的考慮吧。
按官方的說法,插件可以是一個函數或者是包含install函數的對象。Element-ui 可以一次性把所有的組件引入,也可以引入其中某一個,它內部其實使用的就是插件機制。我們動手自己實現一下:
目錄結構如下:
SyElement/index.js:
定義了一個插件,該插件中通過 Vue 提供的全局函數 component 在全局注冊了組件 SyInfo 和 SyMessage,看代碼:
- import SyInfo from './SyInfo/index';
- import SyMessage from './SyMessage/index';
- import log from './log';
- export default {
- install(Vue, options) {
- // 全局注冊組件 SyInfo
- Vue.component(SyInfo.name, SyInfo);
- // 全局注冊組件 SyMessage
- Vue.component(SyMessage.name, SyMessage);
- // 給 Vue 添加一個全局函數,該函數可在所有的組件中使用
- Vue.prototype.$loglog = log;
- }
- }
由于要支持單組件使用,故每個組件其實也是一個插件。
- import SyMessage from './src/component.vue';
- // 提供一個 install 函數
- SyMessage.install = function(Vue) {
- Vue.component(SyMessage.name, SyMessage);
- }
- export default SyMessage;
component.vue 就是一個組件的具體實現:
- <template>
- <div class="sy-info">
- 剖析element-ui的實現方式
- </div>
- </template>
- <script>
- export default {
- name: 'SyMessage'
- }
- </script>
SyMessage 和 SyInfo 的實現一樣。到此便可以和 Element-ui 一樣的方式使用了:
- import ElementUI from 'element-ui';
- Vue.use(ElementUI);
- <template>
- <div>
- <sy-info></sy-info>
- <sy-message></sy-message>
- </div>
- </template>
多說一句:有時候,有些業務需求需要在每個組件中使用某個服務,比如數據統計,其實可以在 Vue 全局中掛載一個函數,這樣在每個組件中即可使用,比如文章提到的 log 就是在全局掛載的一個函數:
- Vue.prototype.$loglog = log;
在所有的組件中既可以這樣使用:
- this.$log({
- uid: 'suyan'
- });