【问题标题】:How to use stylus to access javascript variables in vue file?如何使用手写笔访问 vue 文件中的 javascript 变量?
【发布时间】:2018-12-13 04:36:03
【问题描述】:

例如:

<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>

有没有办法在css中访问javascript变量?可以使用sass或less,但我会 更喜欢手写笔。

【问题讨论】:

    标签: css vue.js sass less stylus


    【解决方案1】:

    我知道这不是“这个”问题的答案(我想发表评论),但我会尝试提供替代解决方案。

    Stylus 支持内置函数json(path[, options]),这意味着您可以将所有变量放入 JSON 文件中,并将它们提供给您的 JS 文件和 Stylus 文件。

    您无法使用 JS 访问 stylus 变量,除非您找到某种可以将指定的 js 文件/变量转换为 stylus 变量的构建时库,否则您可能无法做到这一点。

    【讨论】:

    • 我认为这是一个非常好的答案。它没有直接回答问题,但提出了解决问题的好方向。
    【解决方案2】:

    您可以使用 CSS 自定义属性来实现。

    将手写笔变量与它们绑定,然后只处理 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      相关资源
      最近更新 更多