命名空间+变量管理css样式
在src/styles/variables.module.less定义命名空间:
// 命名空间
@namespace: v;
// el命名空间
@elNamespace: el;
// 导出变量
:export {
namespace: @namespace;
elNamespace: @elNamespace;
}
在页面中使用:
<style lang="less" scoped>
/* namespace已经全局注入,不需要额外在引入 */
@prefix-cls: ~'@{namespace}-app';
.@{prefix-cls} {
width: 100%;
}
</style>
定义生成类名的函数
import variables from '@/styles/variables.module.less'
export const useDesign = () => {
const lessVariables = variables
/**
* @param scope 类名
* @returns 返回空间名-类名
*/
const getPrefixCls = (scope: string) => {
return `${lessVariables.namespace}-${scope}`
}
return {
variables: lessVariables,
getPrefixCls
}
}
在vue/ts中使用
<template>
<div :class="prefixCls">
<h1>home</h1>
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</template>
<script setup lang="ts">
import { useDesign } from '@/hooks/web/useDesign'
// 获取类名
const {getPrefixCls} = useDesign()
const prefixCls = getPrefixCls('home')
</script>