不啰嗦,直接看代码,代码下面会有详细说明。
html<template>
  <div>
    <v-switch
      color="warning"
      v-model="themeValue"
      @update:modelValue="toggleTheme()"
      hide-details
      inset
    >
      <template v-slot:label>
        <v-icon
          :icon="themeValue ? 'mdi-emoticon-cool-outline' : 'mdi-weather-night'"
          :color="themeValue ? 'warning' : 'white'"
        ></v-icon>
      </template>
    </v-switch>
  </div>
</template>
<script setup lang="ts">
// 切换主题开关组件,只负责切换逻辑,不关心主题初始化逻辑
import { useTheme } from "vuetify";
const theme = useTheme(); // vuetify 的 theme 属性
const themeValue = ref(theme.global.name.value == "light"); // 根据theme控制switch开关的变量
const toggleTheme = () => {
  const to = themeValue.value ? "light" : "dark";
  theme.global.name.value = to;
  localStorage.setItem("theme", to);
};
</script>
<style scoped></style>
Nuxt3 环境下编写,所以不需要手动引入 ref 等工具;useTheme 是 vuetify 的工具,用于获取主题信息;v-switch 和 v-icon 是 vuetify 的组件,并使用了 v-slot:label 来自定义名称;v-slot:label 中 使用了 mdi 图标库,该图标库是 vuetify 自动引入,无需其他安装,代码中的 'mdi-emoticon-cool-outline' 即对应一个图标,其他图标请自行了解。theme.global.name.value 是控制主题的变量。本文作者:DingDangDog
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!