天天看點

建立base公共元件

公共子產品

建立base公共元件
基礎子產品參照了​​vant​​的思路,使用​​bem​​命名規範。先建立一個命名空間,這個命名空間傳回建立元件函數與生成命名方法。在建立元件函數中建立​

​name​

​與​

​install​

​屬性用于注冊​

​vue​

​元件

建立元件函數

建立base元件

npm run plop
# 輸入元件名稱得到packages/base子產品
      

在src檔案夾中建立​

​create​

​檔案夾并建立​

​component.ts​

​檔案用于建立元件方法。建立元件與要​

​name​

​屬性和​

​install​

​方法來注冊元件

/**
 * Create a basic component with common options
 */
import { App, defineComponent, ComponentOptionsWithObjectProps } from 'vue'

/**
 *
 * @description 建立元件
 * @export createComponent
 * @param {string} name
 * @return {*} defineComponent
 */
export function createComponent (name: string) {
return function (sfc: ComponentOptionsWithObjectProps) {
sfc.name = name
sfc.install = (app: App) => {
app.component(name as string, sfc)
app.component(name), sfc)
    }

return defineComponent(sfc)
  } as typeof defineComponent
}

      

因為我們元件名字可能包含多個單詞是以我們把他轉換為駝峰命名法是以建立​

​src/format/string.ts​

​檔案來導出駝峰命名函數

// base/src/format/string.ts

const camelizeRE = /-(\w)/g

/**
 *
 * @description 把-換成駝峰命名
 * @export camelize
 * @param {string} str
 * @return {*}  {string}
 */
export function camelize (str: string): string {
return str.replace(camelizeRE, (_, c) => c.toUpperCase())
}

      
// base/src/create/component.ts
import { camelize } from '../format/string'
// 修改這句代碼來轉換為駝峰命名法
app.component(camelize(`-${name}`), sfc)
      

建立​

​create/bem.ts​

​檔案生成​

​bem​

​的函數

Bem 函數傳入參數與生成的名字
  • b() // 'button'
  • b('text') // 'button__text'
  • b({ disabled }) // 'button button--disabled'
  • b('text', { disabled }) // 'button__text button__text--disabled'
  • b(['disabled', 'primary']) // 'button button--disabled button--primary'
export type Mod = string | { [key: string]: any };
export type Mods = Mod | Mod[];

function gen (name: string, mods?: Mods): string {
if (!mods) {
return ''
  }

if (typeof mods === 'string') {
return ` ${name}--${mods}`
  }

if (Array.isArray(mods)) {
return mods.reduce<string>((ret, item) => ret + gen(name, item), '')
  }

return Object.keys(mods).reduce(
    (ret, key) => ret + (mods[key] ? gen(name, key) : ''),
''
  )
}

/**
 *
 * @description 建立BEM命名空
 * @export
 * @param {string} name
 * @return {*} string
 */
export function createBEM (name: string) {
return function (el?: Mods, mods?: Mods): Mods {
if (el && typeof el !== 'string') {
mods = el
el = ''
    }

el = el ? `${name}__${el}` : name

return `${el}${gen(el, mods)}`
  }
}

export type BEM = ReturnType<typeof createBEM>;

      

​create/index.ts​

​檔案,這個檔案導出一個函數這個函數有一個參數,這個參數就是建立元件的名字,傳回一個數組,這個數組的第一項是建立元件的方法,第二項就是根據元件名字建立​

​bem​

​命名規則的函數

import { createBEM } from './bem'
import { createComponent } from './component'

/**
 *
 *  @description 建立命名空間
 * @export
 * @param {string} name
 * @return {*} [createComponent(name), createBEM(name)]
 */
export function createNamespace (name: string) {
name = 'two-' + name
return [createComponent(name), createBEM(name)] as const
}