Appearance
组件辅助
Vue 组件开发辅助工具,提供 BEM 命名空间和组件安装功能。
createNamespace
创建 BEM(Block Element Modifier)命名空间,用于组件 CSS 类名管理。
ts
function createNamespace(name: string): {
n: (suffix?: string) => string
classes: (...classes: Classes) => any[]
}参数
| 参数 | 说明 | 类型 |
|---|---|---|
| name | 组件名,将作为 BEM 的 Block | string |
返回值
返回一个对象,包含:
n(suffix)— 生成 BEM 类名classes(...classes)— 条件类名处理
BEM 规则
| 后缀格式 | 生成类名 | 说明 |
|---|---|---|
| 无后缀 | van-{name} | Block |
--modifier | van-{name}--modifier | Modifier |
__element | van-{name}__element | Element |
示例
ts
import { createNamespace } from 'ljf-utils'
const { n, classes } = createNamespace('button')
// 生成 BEM 类名
n() // 'van-button'
n('--primary') // 'van-button--primary'
n('__icon') // 'van-button__icon'
// 条件类名
classes(
'custom-class',
[true, 'active'], // 条件为 true,返回 'active'
[false, 'disabled'] // 条件为 false,返回 null
)
// ['custom-class', 'active', null]withInstall
为 Vue 组件添加 install 方法,使其支持 app.use() 注册。
ts
function withInstall<T, E extends Record<string, any>>(
main: T,
extra?: E
): SFCWithInstall<T> & E参数
| 参数 | 说明 | 类型 |
|---|---|---|
| main | 主组件 | T |
| extra | 额外导的组件或方法 | E |
示例
ts
import { withInstall } from 'ljf-utils'
import Button from './Button.vue'
import ButtonGroup from './ButtonGroup.vue'
// 为主组件添加 install 方法
const ButtonWithInstall = withInstall(Button, { ButtonGroup })
// 使用
app.use(ButtonWithInstall)
// 同时注册了 Button 和 ButtonGroupwithInstallFunction
为函数组件(如 $toast)添加 install 方法,挂载到全局属性。
ts
function withInstallFunction<T>(fn: T, name: string): SFCInstallWithContext<T>参数
| 参数 | 说明 | 类型 |
|---|---|---|
| fn | 函数组件 | T |
| name | 全局属性名 | string |
示例
ts
import { withInstallFunction } from 'ljf-utils'
import Toast from './Toast'
// 安装后可通过 app.config.globalProperties.$toast 访问
const ToastWithInstall = withInstallFunction(Toast, '$toast')
// 使用
app.use(ToastWithInstall)
// 在组件中
this.$toast('提示内容')