1. 程式人生 > 實用技巧 >vue+iview+less實現主題切換功能

vue+iview+less實現主題切換功能

1. 切換主題,為body新增不同類名

<template>
  <div>
    <Select v-model="theme" @on-change="changeTheme">
      <Option v-for="item in themes" :value="item.value" :key="item.value">{{ item.name }}</Option>
    </Select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      themes: [
        { name: '白色主題', value: 'theme-light' },
        { name: '黑色主題', value: 'theme-dark' },
      ],
      theme: '',
    };
  },
  methods: {
    changeTheme(theme) {
      window.localStorage.setItem('theme', theme);
      // 設定body類
      const body = document.querySelector('body');
      this.themes.forEach((t) => {
        body.classList.remove(t.value);
      });
      body.classList.add(theme);
    },
  },
  created() {
    // 初始化獲取主題
    this.theme = window.localStorage.getItem('theme') || this.themes[0].value;
    // 設定body類
    const body = document.querySelector('body');
    body.classList.add(this.theme);
  },
};
</script>

2. 設定主題函式(theme.func.less中);並給出預設樣式

.theme(@error-color: res, @success-color: green) {
      .error-font {
            font-color: @error-color;
      }
      .success-font {
            font-color: @success-color;
      }
}

3. index.less中呼叫主題函式,進行傳參,根據body類設定不同主題

@import './theme-func.less';
.theme-light{
      .theme();
}
.theme-dark {
      @error-color: yellow;
      @success-color: blur;
      .theme(@error-color, @success-color);
}

4.測試效果

<div class="error-font">錯誤資訊</div>
<div class="success-font">成功資訊</div>

切換主題時,樣式如下:

ps: 本人初始特別想不同主題下只更改less變數,然後在各種樣式和類中引入不同主題的變數進行不同樣式顯示;(有哪位大佬實現了的請求指示一下~~)
奈何研究很久沒有成功,只能不同主題下,設定類的樣式,然後vue中引入定義的類;