美文网首页
Vue中使用Style变量

Vue中使用Style变量

作者: alue | 来源:发表于2022-05-16 19:06 被阅读0次

    Vue能不能实现数据驱动style样式呢?

    官方提供的办法是在 <template> 里使用 :style 或者 :class的方式赋值。但它们有个缺陷,即无法设置 伪元素 的css属性,例如,如果想设置

     .target:hover { background-color: this.color };
    

    就没法用上述方法实现。

    css提供了 var()函数,能够动态设置样式的属性。Vue可以通过下面这两种方法实现对 var()函数的传参。

    方法一 利用documentElement.style动态设置

    mounted () {
       document.documentElement.style.setProperty('--bg-hover-color ', this.color)
    },
    // -----
    .target:hover{
    background-color: var(--bg-hover-color, #ff5722);
    }
    

    方法二(推荐)利用computed属性

    <div class="target" :style="css" />
    
    
    computed: {
        css() {
          return {
            "--bg-hover-color": this.color,
          };
        },
    
    // ---
    
    .target:hover{
    background-color: var(--bg-hover-color, #ff5722);
    }
    
    

    相关文章

      网友评论

          本文标题:Vue中使用Style变量

          本文链接:https://www.haomeiwen.com/subject/sdswurtx.html