Vue-全局組件註冊

一般情況,需要使用組件的場景:

<template>
    <BaseInput  v-model="searchText"  @keydown.enter="search"/>
    <BaseButton @click="search">
        <BaseIcon name="search"/>
    </BaseButton>
</template>

<script>
    import BaseButton from './baseButton'
    import BaseIcon from './baseIcon'
    import BaseInput from './baseInput'
    export default {
      components: { BaseButton, BaseIcon, BaseInput }
    }
</script>

我們寫了一堆基礎UI組件,然後每次我們需要使用這些組件的時候,都得先import,然後聲明components,很繁瑣,這裏可以使用統一註冊的形式

優化

我們需要藉助一下神器webpack,使用 require.context() 方法來創建自己的模塊上下文,從而實現自動動態require組件。這個方法需要3個參數:要搜索的文件夾目錄、是否還應該搜索它的子目錄、以及一個匹配文件的正則表達式。 我們在components文件夾添加一個叫componentRegister.js的文件,在這個文件裏藉助webpack動態將需要的基礎組件統統打包進來。

/src/components/componentRegister.js

import Vue from 'vue'
/**
* 首字母大寫
* @param str 字符串
* @example heheHaha
* <a href="http://www.jobbole.com/members/wx1409399284">@return</a> {string} HeheHaha
*/
function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

/**
* 對符合'xx/xx.vue'組件格式的組件取組件名
* @param str fileName
* @example abc/bcd/def/basicTable.vue
* <a href="http://www.jobbole.com/members/wx1409399284">@return</a> {string} BasicTable
*/

function validateFileName(str) {
  return /^S+.vue$/.test(str) &&
    str.replace(/^S+/(w+).vue$/, (rs, $1) => capitalizeFirstLetter($1))
}

const requireComponent = require.context('./', true, /.vue$/)
// 找到組件文件夾下以.vue命名的文件,如果文件名爲index,那麼取組件中的name作爲註冊的組件名
requireComponent.keys().forEach(filePath => {
  const componentConfig = requireComponent(filePath)
  const fileName = validateFileName(filePath)
  const componentName = fileName.toLowerCase() === 'index'
    ? capitalizeFirstLetter(componentConfig.default.name)
    : fileName
  Vue.component(componentName, componentConfig.default || componentConfig)
})

這裏文件夾結構:

components

│ componentRegister.js

├─BasicTable

│ BasicTable.vue

├─MultiCondition

│ index.vue

這裏對組件名做了判斷,如果是index的話就取組件中的name屬性處理後作爲註冊組件名,所以最後註冊的組件爲:multi-condition、basic-table 最後我們在main.js中import ‘components/componentRegister.js’,然後我們就可以隨時隨地使用這些基礎組件,無需手動引入了~


juejin.im/post/5ae02f39518825672f198ac2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章