I am currently facing an issue with implementing two active themes, a light-theme
and a dark-theme
, within an external button component. I have been successful in making it work by embedding the code and function directly inside the view.
While this setup works as an example, I have encountered a "real world" scenario where I need the functionality to switch between dark and light mode to be operational from within the component itself, dynamically changing the class based on the selected theme.
In my "Home.vue
" file, I import components ButtonA
and ButtomB
:
<template>
<div :class="theme" class="bg-background-primary">
<h1 class="text-4xl text-typo-primary">Test title</h1>
<!-- Inside Home.vue - WORKING -->
<button class="border border-gray-400 bg-blue-500 hover:bg-blue-700 text-white p-2 rounded" @click="toggleThemeOne()">Toggle Dark/Light</button>
<!-- Component with function outside - WORKING -->
<ButtonA msg="From component" @click.native="toggleThemeTwo()" />
<ButtonB msg="Full from component" />
</div>
</template>
<script>
import ButtonA from '@/components/ButtonA.vue'
import ButtonB from '@/components/ButtonB.vue'
export default {
name: 'Home',
components: {
ButtonA,
ButtonB
},
data() {
return {
theme: 'theme-light',
}
},
methods: {
toggleThemeOne() {
this.theme = this.theme === 'theme-light' ? 'theme-dark' : 'theme-light'
localStorage.setItem('theme', this.theme)
console.log('toggleThemeOne working');
console.log(this.theme)
},
toggleThemeTwo() {
this.theme = this.theme === 'theme-light' ? 'theme-dark' : 'theme-light'
localStorage.setItem('theme', this.theme)
console.log('toggleThemeTwo working');
console.log(this.theme)
},
}
}
</script>
Home.vue has a functional button for switching themes
ButtonA
It contains only HTML with the function included in the component
<template>
<div>
<button class="border border-gray-400 bg-blue-500 hover:bg-blue-700 text-white p-2 rounded"> {{ msg }} </button>
</div>
</template>
<script>
export default {
name: "ButtonComp",
props: [
'msg'
]
}
</script>
ButtonB
<template>
<div>
<button
class="border border-gray-400 bg-blue-500 hover:bg-blue-700 text-white p-2 rounded"
@click="toggleThemeTree()"
> {{ msg }} </button>
</div>
</template>
<script>
export default {
name: "ButtonComp",
props: [
'msg'
],
methods: {
toggleThemeTree() {
this.theme = this.theme === 'theme-light' ? 'theme-dark' : 'theme-light'
localStorage.setItem('theme', this.theme)
console.log('toggleThemeTree working');
console.log(this.theme)
},
},
}
</script>
This is the button that is causing issues. The function should update the :class property in Home.vue, but I can only see the values in the console and the :class
is not functioning as expected.
I have previously attempted using $emit
and computed properties
, but unfortunately, these solutions did not yield the desired results.