vue.js - 如何动态定义css选择器属性?
问题描述
有没有办法动态定义 css 选择器属性?
例如,如何使用从后端服务器获取的值定义“.some-style”选择器的“颜色”属性?
<style>
.some-style {
color: #ffc050;
}
</style>
解决方案
- 在模板的最顶层元素中创建动态
style
。 - 将属性的后端响应分配给计算函数。
- 设置样式语言,
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>
推荐阅读
- algorithm - 如何创建一个带有循环的链表?
- sqlite - 每 3 行 Sqlite 总和
- javascript - 反应如何使用样式化组件更改按钮的背景
- javascript - 如何在 Angular 11 中使用 aws-iot-device-sdk NPM 模块?(它在构建时抛出 fs、path 和 tls 错误)
- python - Python - os.walk(在文件资源管理器中搜索文件)对我不起作用
- arrays - 在 C99 中的连续内存中分配两个全局数组
- typescript - 是否可以从 docker-compose 运行命令 npm test?
- wiremock - 使用wiremock时异步测试的ConditionTimeout
- spring-boot - 无法将“server.port”下的属性绑定到 java.lang.Integer
- google-apps-script - 由于错误 401,无法再运行脚本:deleted_client OAuth 客户端已删除