How to use stylus to access javascript variables in vue file?
Asked Answered
S

2

10

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.

Simplicidentate answered 4/7, 2018 at 17:38 Comment(0)
B
8

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.

Bibliology answered 10/7, 2018 at 4:26 Comment(1)
I think it is a very good answer. It doesn’t answer the question directly but suggests a good direction for solving the problem.Hamrnand
C
4

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

Calabresi answered 10/7, 2018 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.