Switch theme color in vue

1. Create a new globalstyle.scss in the styles folder

 

2. Introduce in App.vue

import './styles/globalstyle.scss'

3. Define variables in globalstyle.scss

 :root {      --primary-color: #1890ff; // default theme color      --background-color: #fafafa; // background color      --text-color: #333; // font color    }



4. Use style variables in Vue components and use the CSS attribute var() to reference

 div { background-color: var( --primary-color);}


5. Click to switch the theme

1. Create a theme switching method that uses Vue's computed properties to access style variables. Use Vue's watch option to watch for changes to theme variables.

data() {

 return {
       currentTheme: "default" // 默认主题
     };
   },
   computed: {
     primaryColor() {
       const themes = {
         default: "#1890ff",
         red: "#f5222d",
       };
       return themes[this.currentTheme] || themes.default;
     }
   },
   watch: {
     currentTheme() {
       document.documentElement.style.setProperty(
         "--primary-color",
         this.primaryColor
       );
     }
   },
   methods: {
     switchTheme(theme) {
       this.currentTheme = theme;
     }
   }

2. Use the switch theme function in Vue. You can create a button or dropdown to toggle themes and use style variables in each view component.

  <button @click="switchTheme('default')">Default Theme</button>
  <button @click="switchTheme('red')">Red Theme</button>

Guess you like

Origin blog.csdn.net/qq_39029949/article/details/130521929