Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stylus to access javascript variables in vue file?

For example:

<script>
    export default {
        data() {
            return{
                varinjs: 1,
            }
        }
    }
</script>
<style lang="stylus">
    varincss = varinjs

    body
      if varincss  == 0
        background-color red
      else varincss == 1
        background-color blue
</style>

Is it any way to access javascript variables in css?can use sass or less, but I'd like stylus much more.

like image 498
Mario Avatar asked Jul 04 '18 17:07

Mario


2 Answers

I know this is not an answer to 'this' question (I wanted to comment) but I will try to give an alternate solution.

Stylus supports a built-in function json(path[, options]), which means you can put all variables into a JSON file and supply them both to your JS files as well as Stylus files.

You cannot access stylus variable using JS and you probably won't be able to do that unless you find some sort of build-time libraries that would convert specified js file/variable into stylus variables.

like image 161
rjbaj Avatar answered Nov 19 '22 22:11

rjbaj


You could use CSS custom properties to achieve that.

Bind stylus variables with them and just handle changes on JavaScript.

<script>
  export default {
    data () {
      return {
        theme: { background: '#ff0000' }
      };
    },
    watch: {
      'theme.background': { immediate: true, handler: 'applyVariables' }
    },
    methods: {
      applyVariables () {
        const scope = document.documentElement.styles;
        scope['--theme-background'] = this.theme.background;
      }
    }
  };
</script>

<style lang="stylus">
  theme-background = var(--theme-background, #ff054a);
  // The first argument is variable name and second is placeholder value.

  .theme-button
    background-color: theme-background
</style>

CSS Custom Properties reference on MDN

like image 4
VitorLuizC Avatar answered Nov 19 '22 21:11

VitorLuizC