Vue中使用Style变量

2022-05-16  本文已影响0人  alue

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);
}

上一篇下一篇

猜你喜欢

热点阅读