Vue动态更改/设置元素样式

  • Post author:
  • Post category:vue




1.

写在methods里, :style动态绑定方法返回的属性

<div>
	<span class="res" v-for="(data, index) in data" :key="index">
	<!-- 当传不同的值时会渲染出不同颜色的方块 -->
    <span :style="giveColor(data)">
         {{index + 1}}
     </span>
 </span>
</div>
// 定义一个数组, 放所有可能的颜色, 用swatch来判断返回那种颜色, return后不要用background-color, 要转换成backgroundColor驼峰,属性对应的的值要用引号包裹
 giveColor(num) {
        let colorArray = ["green", "red", "white", "yellow"];
        let color = "";
        switch (num) {
            case 1:
              color = colorArray[num - 1];
              break;
            case 2:
              color = colorArray[num - 1];
              break;
            case 3:
              color = colorArray[num - 1];
              break;
            case 4:
              color = colorArray[num - 1];
              break;
        }
        return {
            display: "inline-block",
            width: "100%",
            height: "100%",
            backgroundColor: color,
        };
      }



2.

放在data()里

<div>
	<span class="res" v-for="(data, index) in data" :key="index">
	<!-- 直接绑定 -->
    <span :style="styleData">
         {{index + 1}}
     </span>
 </span>
</div>
export default {
    data() {
      return {
        styleData: {
          display: "inline-block",
          width: "100%",
          height: "100%",
          backgroundColor: "red",
        }
   	  }
    }
}



其他情况应变就好, 不管怎样记得属性要驼峰, 值用引号包裹



版权声明:本文为weixin_44076273原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。