Vuetify实现明暗主题切换按钮
## 组件代码 不啰嗦,直接看代码,代码下面会有详细说明。 ```html <template> <
渲染中...
## 组件代码
不啰嗦,直接看代码,代码下面会有详细说明。
```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>
```
<!-- more -->
## 代码说明
1. 代码是在 `Nuxt3` 环境下编写,所以不需要手动引入 `ref` 等工具;
2. `useTheme` 是 `vuetify` 的工具,用于获取主题信息;
3. `v-switch` 和 `v-icon` 是 `vuetify` 的组件,并使用了 `v-slot:label` 来自定义名称;
4. `v-slot:label` 中 使用了 `mdi` 图标库,该图标库是 `vuetify` 自动引入,无需其他安装,代码中的 `'mdi-emoticon-cool-outline'` 即对应一个图标,其他图标请自行了解。
5. `theme.global.name.value` 是控制主题的变量。
END
评论
登录后查看和发表评论
前往登录