博客 分类专栏 专题 成员
Vue3切换风格
2023-02-10 03:55:23
分类专栏: Vue3

我们想要实现风格切换,基本思路就是定制一套基本的样式,然后不同的风格,我们使用不同的颜色,通过最外层添加class选择器来进行覆盖,达到切换风格效果。

演示

图片

获取风格

在最外层的app.vue中,从本地存储中获取风格样式,vue的最外层会有一个#app的id,我们改变这个dom的class
App.vue

<template>
  <div>
    <router-view />
  </div>
</template>

<script setup>
import { onMounted } from "vue";

const init = () => {
  let theme = localStorage.getItem("theme");
  if (theme == null || theme == "base") {
    theme = "base";
  } else {
    theme = "base " + theme;
  }
  const parentNode = document.querySelector("#app");
  parentNode.setAttribute("class", theme);
};

onMounted(() => {
  init();
});
</script>

<style lang="scss">
</style>

定义多套风格样式

:root {
    --background-base: #409eff;
    --background-green: #67c23a;
    --background-red: #f56c6c;

    --font-color-base: #fff;
    --font-color-green: #fff;
    --font-color-red: #fff;
}

.base {
    .el-button {
        background: var(--background-base);
        color: var(--font-color-base)
    }
}

.green {
    .el-button {
        background: var(--background-green);
        color: var(--font-color-green)
    }

}

.red {
    .el-button {
        background: var(--background-red);
        color: var(--font-color-red)
    }

}

切换风格

注意这里只是简单的演示下切换风格,我们引入element-plus,切换风格来切换按钮的颜色。
ChangeTheme.vue

<template>
  <div>
    <div class="theme-list">
      <span
        v-for="item in themeList"
        :style="{ background: item.color }"
        @click="changeTheme(item)"
      >
      </span>
    </div>
    <div class="content-list">
      <el-button>按钮</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
const { proxy } = getCurrentInstance();

const themeList = [
  {
    className: "base",
    color: "#409eff",
  },
  {
    className: "green",
    color: "#67c23a",
  },
  {
    className: "red",
    color: "#f56c6c",
  },
];

const changeTheme = (item) => {
  localStorage.setItem("theme", item.className);
  let theme = "base " + (item.className == "base" ? "" : item.className);
  const parentNode = document.querySelector("#app");
  parentNode.setAttribute("class", theme);
};
</script>

<style lang="scss" scoped>
.theme-list {
  display: flex;
  span {
    cursor: pointer;
    width: 30px;
    height: 30px;
    display: block;
  }
}
.content-list {
  margin-top: 10px;
}
</style>