1// 默认命名前缀
2export const defaultNamespace = "b";
3
4export const useNamespace = (block) => {
5 // 命名前缀就是命名空间
6 const namespace = defaultNamespace;
7 return {
8 namespace,
9 };
10};
11
12/**
13 * _bem
14 * @param namespace 命名空间
15 * @param block 块
16 * @param blockSuffix 子级块
17 * @param element 元素
18 * @param modifier 修改器
19 * @param modifierValue 修改器的值
20 * @returns className
21 */
22const _bem = (
23 namespace,
24 block,
25 blockSuffix,
26 element,
27 modifier,
28 modifierValue
29) => {
30 // 默认 Block,例如:suit-tags
31 let className = `${namespace}-${block}`;
32 // 如果存在子级块,例如:suit-tags-wrap
33 blockSuffix && (className += `-${blockSuffix}`);
34 // 如果存在元素,例如:suit-tags-wrap__item
35 element && (className += `__${element}`);
36 // 如果存在修改器,例如:suit-tags-wrap__item--size
37 modifier && (className += `--${modifier}`);
38 // 如果存在修改器的值,例如:suit-tags-wrap__item--size_mini
39 modifierValue && (className += `_${modifierValue}`);
40 // 返回
41 return className;
42};
:::
1export const useNamespace = (block) => {
2 // 命名前缀就是命名空间
3 const namespace = defaultNamespace;
4
5 // 生成 Block
6 const b = (blockSuffix = "") => _bem(namespace, block, blockSuffix, null, null, null);
7 return {
8 namespace,
9 b,
10 };
11};
1export const useNamespace = (block) => {
2 // 命名前缀就是命名空间
3 const namespace = defaultNamespace;
4
5 // 生成 Block(块)
6 const b = (blockSuffix = "") =>
7 _bem(namespace, block, blockSuffix, null, null, null);
8 // 生成 Element(元素)
9 const e = (element) =>
10 element ? _bem(namespace, block, null, element, null, null) : "";
11 return {
12 namespace,
13 b,
14 e,
15 };
16};
1export const useNamespace = (block) => {
2 // 命名前缀就是命名空间
3 const namespace = defaultNamespace;
4
5 // 生成 Block(块)
6 const b = (blockSuffix = "") =>
7 _bem(namespace, block, blockSuffix, null, null, null);
8 // 生成 Element(元素)
9 const e = (element) =>
10 element ? _bem(namespace, block, null, element, null, null) : "";
11 // 生成 Modifier(修改器)
12 const m = (modifier, value) =>
13 modifier ? _bem(namespace, block, null, null, modifier, value) : "";
14 return {
15 namespace,
16 b,
17 e,
18 m,
19 };
20};
使用
components/button/src/button.vue
1<script lang="ts" setup>
2import { useNamespace } from "@better-ui/hooks";
3defineOptions({
4 name: "BButton",
5});
6const ns = useNamespace("button");
7</script>
8
9<template>
10 <button :class="[ns.b(), ns.m('primary')]">这是一个测试的按钮</button>
11</template>