使用vue-cli初始化一個項目:
vue init webpack VueComponentcd VueComponentnpm installnpm run dev
以上就新建好了一個vue項目
項目目錄首先,定義好目錄,經過觀察大多數的組件庫,基本是這樣的目錄:
|-- examples // 用於demo展示|-- packages // 用於編寫存放組件
因為修改了目錄名稱,就需要修改下webpack的配置文件,修改編輯目錄
build/webpack.bash.config.js
{ test: /\.js$/, loader: 'babel-loader', include: [resolve('examples'), resolve('test'), resolve('node_modules/webpack-dev-server/client'),resolve('packages')]}
將編譯目錄指向examples和packages。
寫一個組件在packages下面創建一個Button組件,目錄如下(目錄構建都是參照ele-ui)
|-- examples |-- packages | |--Button| |--src| | |--main.vue // 編寫組件內容| |-- index.js // 導出組件
main.vue內容:
<template> <div> button按鈕組件 </div></template><script> export default{ name: 'MButton', // 定義這個組件的名稱 }</script>
index.js內容:
import Button from './src/main.vue';// 在每個組件下面定義一個install方法。Button.install = function (Vue) { Vue.component(Button.name, Button);};export default Button;
到此,就完成了一個組件的簡單編寫
導出組件組件寫好之後,需要讓組件支持全局引入和按需引,在packages下面新建一個index.js文件,用於將組件導出
代碼:
import Button from './button/index.js'; // 引入組件const components = [ Button];//'vue-use是調用的install方法'const install = function(Vue) { if (install.installed) return; components.map(component => Vue.component(component.name, component));};if (typeof window !== 'undefined' && window.Vue) { console.log('傳入參數install方法') install(window.Vue);}export default { install, // 如果在外面使用vue.use的話,就會默認使用install方法 Button};
這裡為什麼要定義一個install方法呢?看下vue源碼
import { toArray } from '../util/index'export function initUse (Vue: GlobalAPI) { Vue.use = function (plugin: Function | Object) { const installedPlugins = (this._installedPlugins || (this._installedPlugins = [])) if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters const args = toArray(arguments, 1) args.unshift(this) ⚠️ if (typeof plugin.install === 'function') { ⚠️ plugin.install.apply(plugin, args) } else if (typeof plugin === 'function') { plugin.apply(null, args) } installedPlugins.push(plugin) return this }}
由此可見,vue.use是調用傳入的組件的instll方法。這也就解釋了,為什麼每個組件都定義了一個install方法。
使用組件在examples的main.js裡面引入組件:
import MVUI from '../packages/index'Vue.use(MVUI)
到此,一個非常簡單的組件就寫好了。