use shared dark mode state in BootstrapThemeSwitch.vue to support multiple instances of switches to be in sync
This commit is contained in:
@@ -1,37 +1,49 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {Options, Vue} from 'vue-class-component';
|
import {Options, Vue} from 'vue-class-component';
|
||||||
|
import {reactive} from 'vue';
|
||||||
|
import {Watch} from 'vue-property-decorator';
|
||||||
|
|
||||||
|
const sharedDarkMode = reactive({
|
||||||
|
internalDarkMode: false,
|
||||||
|
internalLoaded: false,
|
||||||
|
|
||||||
|
get darkMode() {
|
||||||
|
if (!this.internalLoaded) {
|
||||||
|
this.internalDarkMode = localStorage.getItem('darkmode') === ('' + true);
|
||||||
|
this.internalLoaded = true;
|
||||||
|
}
|
||||||
|
return this.internalDarkMode;
|
||||||
|
},
|
||||||
|
|
||||||
|
set darkMode(value: boolean) {
|
||||||
|
this.internalDarkMode = value;
|
||||||
|
localStorage.setItem('darkmode', '' + this.internalDarkMode);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
@Options({
|
@Options({
|
||||||
name: 'BootstrapThemeSwitch',
|
name: 'BootstrapThemeSwitch',
|
||||||
})
|
})
|
||||||
export default class BootstrapThemeSwitch extends Vue {
|
export default class BootstrapThemeSwitch extends Vue {
|
||||||
private darkInternal: boolean = false;
|
get sharedDarkMode() {
|
||||||
|
return sharedDarkMode;
|
||||||
|
}
|
||||||
|
|
||||||
mounted(): void {
|
mounted(): void {
|
||||||
this.readSetting();
|
this.onThemeChanged(this.dark);
|
||||||
this.updateTheme();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private get dark(): boolean {
|
get dark(): boolean {
|
||||||
return this.darkInternal;
|
return this.sharedDarkMode.darkMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
private set dark(value: boolean) {
|
set dark(value: boolean) {
|
||||||
this.darkInternal = value;
|
this.sharedDarkMode.darkMode = value;
|
||||||
this.updateSetting();
|
|
||||||
this.updateTheme();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private readSetting(): void {
|
@Watch('dark', {immediate: true})
|
||||||
this.darkInternal = localStorage.getItem('darkmode') === ('' + true)
|
private onThemeChanged(isDarkMode: boolean): void {
|
||||||
}
|
if (isDarkMode) {
|
||||||
|
|
||||||
private updateSetting(): void {
|
|
||||||
localStorage.setItem('darkmode', '' + this.darkInternal);
|
|
||||||
}
|
|
||||||
|
|
||||||
private updateTheme(): void {
|
|
||||||
if (this.darkInternal) {
|
|
||||||
document.documentElement.setAttribute('data-bs-theme', 'dark');
|
document.documentElement.setAttribute('data-bs-theme', 'dark');
|
||||||
} else {
|
} else {
|
||||||
document.documentElement.removeAttribute('data-bs-theme');
|
document.documentElement.removeAttribute('data-bs-theme');
|
||||||
|
|||||||
Reference in New Issue
Block a user