Home > database >  what's the proper way to implement darkmode in VueJs with SASS using variables
what's the proper way to implement darkmode in VueJs with SASS using variables

Time:04-13

What is the best implementation for dark-mode toggle feature if I am using sass with VueJS
i have a project with sass variables for the colors.

/* variables */
/* ------------- */
$bg-main: #f8f8f8;
$btn-secondary-c: #f6f6f6;
$bg-items: #fff;
$text-c-1: #625f6e;
$text-c-2: #5e5873;
$color-main: #6e6b7b;
$shadow-c: rgba(34, 41, 47, 0.05);
/* ------- */

and it has its own file and globaly scoped to my vue application

src
--components
--assets
----_variables.scss

and my Vue components are created in SFC(Single File Components) style like so

<template>
  <main>
    <div >
      <ProductsSection/>
    </div>
  </main>
</template>

<script>
import ProductsSection from "./ProductsSection.vue"
  export default {
    name: 'MainSection',
    components: {
      ProductsSection,
    },
  }
</script>

<style lang="scss" scoped>
.content-wrapper{
  background-color: $bg-main;
}
</style>

my question is what is the best implementation for this situation?

CodePudding user response:

I really like to modifiy the html attribute:

// index.html
<html lang="en" data-theme="dark">
...
</html>
// App.vue
<template>
<button @click="changeTheme('light')">light theme</button>
<button @click="changeTheme('dark')">dark theme</button>
</template>

<script>
methods: {
  changeTheme(newTheme) {
     document.documentElement.setAttribute('data-theme', newTheme)
  }
}
</script>

<style lang="scss">
@import "./assets/style.scss";
</style>
// style.scss
[data-theme="dark"] {
  --bg-color1: #121416;
  --font-color: #f4f4f4;
}
[data-theme="light"] {
  --bg-color1: #f4f4f4;
  --font-color: #121416;
}
...
body {
  background-color: var(--bg-color1);
  color: var(--font-color);
}

I hope you get the idea

  • Related