使用vue-cli初始化一个项目:vue
vue init webpack VueComponent cd VueComponent npm install npm run dev
以上就新建好了一个vue项目node
首先,定义好目录,通过观察大多数的组件库,基本是这样的目录:webpack
|-- examples // 用于demo展现 |-- packages // 用于编写存放组件
由于修改了目录名称,就须要修改下webpack的配置文件,修改编辑目录
build/webpack.bash.config.jsweb
{ test: /\.js$/, loader: 'babel-loader', include: [resolve('examples'), resolve('test'), resolve('node_modules/webpack-dev-server/client'),resolve('packages')] }
将编译目录指向examples和packages。vue-cli
在packages下面建立一个Button组件,目录以下(目录构建都是参照ele-ui)npm
|-- examples |-- packages | |--Button | |--src | | |--main.vue // 编写组件内容 | |-- index.js // 导出组件
main.vue内容:bash
<template> <div class="M_button"> button按钮组件 </div> </template> <script> export default{ name: 'MButton', // 定义这个组件的名称 } </script>
index.js内容:babel
import Button from './src/main.vue'; // 在每一个组件下面定义一个install方法。 Button.install = function (Vue) { Vue.component(Button.name, Button); }; export default Button;
到此,就完成了一个组件的简单编写app
组件写好以后,须要让组件支持全局引入和按需引,在packages下面新建一个index.js文件,用于将组件导出
代码:webpack-dev-server
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)
到此,一个很是简单的组件就写好了。