I have a script that toggles darkmode component which I have added to my index.html file in my public folder. Decided to move it to my view's itself and render on mounted. Not sure if I am doing it correctly though since it does not change to darkmode once toggled.
Here is the initial script I added to index.html in public folder:
const checkbox = document.querySelector('#checkbox');
const html = document.querySelector('html');
const toggleDarkMode = function () {
checkbox.checked
? html.classList.add('dark')
: html.classList.remove('dark');
}
toggleDarkMode();
checkbox.addEventListener('click', toggleDarkMode);
Here I am moving it to my view and load once mounted:
<script>
import Darkmode from '../components/Darkmode.vue';
import Footer from '../components/Footer.vue';
export default {
name: 'About',
components: {
Darkmode,
Footer,
},
mounted() {
const checkbox = document.querySelector('#checkbox');
const html = document.querySelector('html');
const toggleDarkMode = () => (
checkbox.checked ? html.classList.add('dark') :
html.classList.remove('dark')
);
toggleDarkMode();
},
};
</script>
Just for reference here is the DarkMode.vue component which toggles the mode:
<template>
<div >
<span >
<i ></i>
</span>
<div>
<input id="checkbox" name="" type="checkbox"/>
<label for="checkbox">
<div >
<div ></div>
</div>
</label>
</div>
<span >
<i ></i>
</span>
</div>
</template>
<script>
export default {
name: 'Darkmode',
props: {
msg: String,
},
};
</script>
Am I missing something or this suppose to work?
CodePudding user response:
If, as I understand, you intend to trigger the dark mode when activating your checkbox, it doesn't make much sense for you to place your logic in a lifecycle event like mounted. You can try using v-model and watch:
<template>
<div >
<span >
<i ></i>
</span>
<div>
<input v-model="checkboxOn" id="checkbox" name="" type="checkbox"/>
<label for="checkbox">
<div >
<div ></div>
</div>
</label>
</div>
<span >
<i ></i>
</span>
</div>
</template>
<script>
import Darkmode from '../components/Darkmode.vue';
import Footer from '../components/Footer.vue';
export default {
name: 'About',
components: {
Darkmode,
Footer,
},
data: () => ({
checkboxOn: 0,
}),
watch:{
toggleDarkMode(){
// This isn't a 'vue-style' procedure. I think you should try to communicate with your darkmode.vue component using Vuex, event bus, props...
this.checkboxOn ? document.querySelector('html').classList.add('dark') :
document.querySelector('html').classList.remove('dark')
}
}
};
</script>