我正在开发一个 NuxtJS 网站,页面/组件可以默认采用通用设计,也可以由客户自定义,并将在 url 中指定。
单行的东西:
http://localhost:3000/registration
- 对于通用页面
http://localhost:3000/client-name/registration
- 客户特定页面
为了实现这个目标,我为每个客户端(比如 client-name.json
)准备了一个具有这种结构的 JSON 配置文件。
{
"some_configuration_property": {},
"another_configuration_property": {},
"design": {
"logoUrl": "/assets/client-name/logo.png",
"backgroundColor": "#000000",
"primaryColor": "#ffffff",
"secondaryColor": "#ffff00"
},
}
首先,我实现了路由系统,我可以根据当前路由成功读取每个客户端的配置(在该路由的 Vue 文件的 <script>
标记内),在设置方法内(我使用 @nuxt/组合-api)。
我现在面临的问题是弄清楚如何将这些“设计变量”传递给 <style>
我的 Vue 文件的标签,它使用 SCSS。我想要实现的行为是为特定组件/页面提供默认设计,但可以被每个客户特定的这些“设计变量”覆盖。
- 我首先想到的是使用 CSS 变量,即 将允许我创建具有默认值的变量,但我 将能够覆盖样式内部。我创建了一个用于测试的示例组件,它使用 CSS 属性和 v-deep 伪元素。但是,这意味着我必须为自定义组件中的每个客户端创建一个类,而这正是我想避免的。我首先想到这种方法是因为它可以让我更灵活地选择如何在样式中使用这些设计颜色。
例子:
// From the customizable component
.my-button {
color: (--button-color, teal);
}
// Styling from a parent component/view
// Had to create a selector with a style like <div> for superior specificity though, not so clean
v::deep {
div {
&.my-button {
--button-color: purple;
}
}
}
我看过
/deep/
选择器或::v-deep
伪选择器,但我认为这不是一个非常干净的解决方案,因为它会在代码库中大量使用。来自 parent 的样式组件会使代码难以维护。另一种方法是传递一个变量,
classArray
例如,在 setup 方法中动态绑定(bind) DOM 元素上的 CSS 类。虽然,为每个客户端创建一个具有关联样式的 CSS 类太麻烦了。
像这样:
<template>
<my-button :class="classArray"></my-button>
</template>
<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api'
export default defineComponent({
name: 'MyPage',
setup() {
const clientName = 'someClientName';
const classArray = [clientName]
return { classArray };
},
})
</script>
<style lang="scss" scoped>
.someClientName {
// some custom styles
}
</style>
在这种情况下您会采取什么方法?
感谢您的帮助!
最佳答案
如果需要在运行时加载自定义主题配置,这需要使用CSS变量(属性)。它们可以包装在 SCSS 函数中并具有默认主题回退:
// theme.scss
$primaryColor: #abc;
// $buttonColor: $primaryColor
@function primaryColor() {
@return #{var(--primary-color, $primaryColor)}
}
@function buttonColor() {
@return #{var(--button-color, primaryColor())}
}
然后使用 primaryColor()
等而不是像在常规 SCSS 主题中那样直接使用 $primaryColor
等:
// From the customizable component
.my-button {
color: buttonColor();
}
自定义主题可以在加载时应用于整个文档或应受自定义主题影响的部分文档(组件的层次结构):
const config = await loadClientConfig();
document.documentElement.style.setProperty(--primary-color, config.design.primaryColor)
关于javascript - Vue.js/NuxtJS - 如何创建具有可通过 JSON 配置文件自定义的默认设计的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68703380/