如何使用vue寫一個組件庫

如何使用vue寫一個組件庫

新建vue項目

使用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)

到此,一個很是簡單的組件就寫好了。

相關文章
相關標籤/搜索