const isLight = window.matchMedia('(prefers-color-scheme: light)').matches;
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
那么我们就可以这样,
<script setup>
import TheWelcome from '../components/TheWelcome.vue'
import {reactive, ref, watch} from "vue";
const value = ref('')
import {onMounted} from "vue";
//是否为黑暗模式
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
//模式光亮模式
let theme = ref('light')
//一开始就做判断,theme是动态的
onMounted(()=>{
theme.value = isDarkMode?'dark':'light'
})
script>
<template>
<main>
<van-config-provider :theme="theme"/>
main>
template>
然后再加上,每当用户改变黑暗或者光明模式,都加上监听事件
let mqList = window.matchMedia('(prefers-color-scheme: dark)');
mqList.addEventListener('change', (event) => {
// is dark mode
if (event.matches) {
console.log('变暗')
theme.value = 'dark'
} else {
// not dark mode
console.log('变光')
theme.value = 'light'
}
});
他的设置方法是加入一个组件,而这个组件会自动地渲染所有的vant组件变成暗黑模式
在任意地方加上
<van-config-provider theme="dark"/>
这句话,就会让所有的vant组件变成暗黑模式了
官方说是这么说,但是我真的没有成功过。。。。
vant官方设置了一套暗黑模式的css,如果我们不想的话,可以自己设置
<van-config-provider
:theme-vars="themeVars"
:theme-vars-dark="themeVarsDark"
:theme-vars-light="themeVarsLight"
>
theme-vars-dark
: 仅在深色模式下生效的 CSS 变量,优先级高于 theme-vars
中定义的变量。theme-vars-light
: 仅在浅色模式下生效的 CSS 变量,优先级高于 theme-vars
中定义的变量。import { ref } from 'vue';
export default {
setup() {
const themeVars = { buttonPrimaryBackground: 'red' };
const themeVarsDark = { buttonPrimaryBackground: 'blue' };
const themeVarsLight = { buttonPrimaryBackground: 'green' };
return {
themeVars,
themeVarsDark,
themeVarsLight,
};
},
};
这个就更简单了
<script setup>
import { useDark} from '@vueuse/core'
//直接调用库,判断是否为暗黑,而且是响应式的
let isDark = useDark()
// computed,根据isDark变化而变化
const theme = computed(()=>isDark.value?'dark':'light')
script>
<template>
<div>
<van-config-provider :theme="theme"/>
当前是否为暗黑模式:{{theme}}
div>
template>
如果想要在isDark发生变化时,进行某些操作,可以直接在里面写个函数
const isDark = useDark(
// options 配置项,其中有个函数可以写的
{
onChanged(dark) {
console.log('改变了颜色,dark值当前为:' + dark)
}
}
)