首页 > 解决方案 > 如何动态定义css选择器属性?

问题描述

有没有办法动态定义 css 选择器属性?

例如,如何使用从后端服务器获取的值定义“.some-style”选择器的“颜色”属性?

<style>
    .some-style {
        color: #ffc050;
    }
</style>

标签: vue.jsvuetify.js

解决方案


  1. 在模板的最顶层元素中创建动态style
  2. 将属性的后端响应分配给计算函数。
  3. 设置样式语言,lang='scss'然后使用 CSS 变量函数var()来设置值。

例子

<template>
    <div :style="cssProps">
        <div class="some-style">
            Hello Mars
        </div>
    </div>
</template>

<script>
export default {
computed: {
    cssProps() {
        // backend response with your css values
        let backendResponseObject = {
            fontColor: "black", // you can use rgb or hex
            backgroundColor: "White" // you can use rgb or hex
        }

        properties = {
            "--brand-base": backendResponseObject.color,
            "--brand-primary": backgroundColor.hex,
        };

        return properties;
    }
}
}
</script>

<style lang="scss">
.some-style {
    color: var(--brand-base);
    background: var(--brand-primary);
}
</style>

推荐阅读