Vuetify自定义主题:如何在组件样式中引用主题颜色变量
Problem
I've manually configured a custom Vuetify theme in my index.js with company-specific colors:
Vue.use(Vuetify, { theme: { primary: '#377ef9', secondary: '#1b3e70', accent: '#ff643d', error: '#ff643d' // Additional color definitions } })
I can use these colors in templates via the color prop like this:
<my-text-field name="input text" label="text" value="text text text text..." type="text" color="primary"></my-text-field>
But I want to reuse these theme variables (like secondary) in the scoped Stylus styles of my custom components (e.g., a component extending VTextField), instead of hardcoding hex values. This would let me maintain color consistency and avoid typos/duplication:
<script> import { VTextField } from 'vuetify' export default { extends: VTextField } </script> <style scoped lang="stylus"> label // Desired: Use theme's secondary color here // color: #1b3e70 (works but is not ideal) </style>
Solutions
1. Use Vuetify's Auto-Generated CSS Custom Properties
When you set up a Vuetify theme, the framework automatically injects global CSS custom properties (variables) onto the root element. These follow the pattern --v-theme-{colorName}:
--v-theme-primarymaps to your theme'sprimarycolor--v-theme-secondarymaps to your theme'ssecondarycolor
You can directly reference these variables in your scoped Stylus styles using the var() function:
<style scoped lang="stylus"> label color: var(--v-theme-secondary) </style>
This is the simplest approach—no extra script logic needed, just leverage Vuetify's built-in variable injection.
2. Fetch Theme Variables via Vue Instance & Bind to Styles
For more control (e.g., supporting light/dark theme switching or dynamic theme updates), you can access the theme object via this.$vuetify.theme in your component, then bind the color values to your styles using Vue's v-bind syntax:
<script> import { VTextField } from 'vuetify' export default { extends: VTextField, computed: { secondaryColor() { // Get the current active theme (light/dark) const activeTheme = this.$vuetify.theme.dark ? 'dark' : 'light' return this.$vuetify.theme.themes[activeTheme].secondary } } } </script> <style scoped lang="stylus"> label // Bind the computed color value to the style color: v-bind('secondaryColor') </style>
This method automatically updates your styles if the user switches between light and dark mode, keeping your component in sync with the active theme.
Notes
- If you're using Vuetify 3, the CSS variable naming pattern changes slightly (e.g.,
--v-primary-baseinstead of--v-theme-primary), so adjust the variable names accordingly. - The CSS custom properties from Solution 1 are global, so they work even in scoped styles since they're defined on the root element.
内容的提问来源于stack exchange,提问作者Narxx




