Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to share variable between SASS and Javascript in Vuex(Nuxt)?

As in question. I use Vue, Vuex(Nuxt) and we also share all mixins and sass variables using: @nuxtjs/style-resources": "^1.0.0"

Which is newer version of "nuxt-sass-resources-loader": "^2.0.5"

I know that there i spossibility with Webpack such as here So my question is - is it posiibile to do it in similar way and how to configure it? What should I have installed and how can I add it to my nuxt.config.js?

EDIT: I also found that article but for me it is not working.

like image 975
Mieszczańczyk S. Avatar asked Jan 26 '23 22:01

Mieszczańczyk S.


1 Answers

Short answer: yes.

SASS offers the option to export variables, which you can import as module and use like any other object. Webpack with sass-loader and node-sass handles the imports.

Example:

// in assets/scss/variables.scss

$white-color: #fcf5ed;

// the :export directive is the magic sauce for webpack
:export {
  whitecolor: #{$white-color};
}

// in store.js

import Styles from '~/assets/scss/variables.scss'

export const state = () => ({
  styles: {...Styles}
})

// in component
...
computed: {
  styles() {
    return this.$store.state.styles;
  }
}

Longer answer: You can also just use css variables for everything.

E.g.

// in assets/scss/variables.scss

$white-color: #fcf5ed;

:root {
  --whitecolor: #{$white-color};
}

// in component
...
mounted() {
  this.$el.style.color = 'var(--whitecolor)';
}

<style>
.component {
  color: var(--whitecolor);
}
</style>
like image 162
MarcRo Avatar answered Jan 31 '23 09:01

MarcRo