公共模块

根底模块参照了vant的思路,应用bem命名标准。先创立一个命名空间,这个命名空间返回创立组件函数与生成命名办法。在创立组件函数中创立nameinstall属性用于注册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.tsconst 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.tsimport { 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}

后续的公共的货色也会提取到公共base模块中

原文地址:https://kspf.xyz/archives/142/