在 Vue 自定义组件中使用 CSS 变量来设置样式,你可以通过在组件的样式中使用 var(–variable-name) 来引用 CSS 变量。然后,在组件的根元素或具体的元素上,使用 :style 绑定来动态设置 CSS 变量的值。以下是一个示例代码。
子组件 (CustomComponent.vue)
<template><div :style="{ '--bg-color': backgroundColor }"><slot></slot></div>
</template><script>
export default {props: {backgroundColor: {type: String,default: 'white' // 默认背景色为白色}}
}
</script><style scoped>
/* 组件样式 */
div {padding: 20px;border: 1px solid #ccc;background-color: var(--bg-color); /* 使用 CSS 变量设置背景色 */
}
</style>
在这个示例中,我们在子组件的样式中定义了一个名为 --bg-color 的 CSS 变量,并在组件的根元素中使用它来设置背景色。然后,我们在组件的 backgroundColor prop 中接收父组件传递过来的背景色值,并将其动态设置为 CSS 变量 --bg-color 的值。
父组件
<template><div><custom-component :background-color="bgColor"><h1>Custom Component with Dynamic Background Color</h1><p>This is a custom component with dynamic background color.</p></custom-component><button @click="changeColor">Change Background Color</button></div>
</template><script>
import CustomComponent from './CustomComponent.vue';export default {components: {CustomComponent},data() {return {bgColor: 'lightblue'};},methods: {changeColor() {this.bgColor = 'lightgreen'; // 将背景色改为 lightgreen}}
}
</script>
在这个示例中,我们将父组件中的 bgColor 数据通过 background-color prop 传递给子组件,子组件将其作为 CSS 变量 --bg-color 的值来设置背景色。这样,通过修改 bgColor 数据,你可以动态改变子组件的背景色。