关于javascript:创建base公共组件

16次阅读

共计 2383 个字符,预计需要花费 6 分钟才能阅读完成。

公共模块

根底模块参照了 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.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
}

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

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

正文完
 0