vue中Class 与 Style 绑定

一、绑定class

1、对象语法

<template>
  <div>
    // 1、给 v-bind:class 传入一个对象,以动态地切换 class
    <div v-bind:class="{ active: isActive }">123</div>

    // 2、在对象中传入更多字段来动态切换多个 class
    <div
      class="static"
      v-bind:class="{ active: isActive, 'text-danger': hasError }"
    >
      456
    </div>

    // 3、绑定的数据对象不必内联定义在模板里
    <div v-bind:class="classObject">789</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isActive: true,
      hasError: true,
      
      classObject: {
        active: true,
        "text-danger": false,
      },
    };
  },
};
</script>
<style scoped>
.static {
  font-weight: bold;
}
.active {
  border: 1px solid;
}
.text-danger {
  color: red;
}
</style>

2、数组语法

<template>
  <div>
    // 1、给 v-bind:class 传入一个数组
    <div v-bind:class="[activeClass, errorClass]">123</div>

    // 2、可以用三元表达式,根据条件切换class
    <div v-bind:class="[isActive ? activeClass : '', errorClass]">456</div>

    // 3、当有多个条件 class时,可以在数组语法中也可以使用对象语法
    <div v-bind:class="[{ active: isActive }, errorClass]">789</div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      activeClass: "active",
      errorClass: "text-danger",

      isActive: false,
    };
  },
  methods: {},
};
</script>

<style scoped>
.active {
  font-weight: bold;
}
.text-danger {
  color: red;
}
</style>

绑定内联样式(style)

1、对象语法

<template>
  <div>
    // 1、在模板中直接绑定
    <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">
      123
    </div>

    // 2、绑定一个样式对象(推荐,这会让模板更清晰)
    <div v-bind:style="styleObject">456</div>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      activeColor: "red",
      fontSize: 30,

      styleObject: {
        color: "red",
        fontSize: "13px",
      },
    };
  },
};
</script>

<style scoped>
</style>

2、数组语法

<template>
  <div>
    <div v-bind:style="[baseStyles, overridingStyles]">123</div>
	
	// 多重值(这样写只会渲染数组中最后一个被浏览器支持的值。在本例中,如果浏览器支持不带浏览器前缀的 flexbox,那么就只会渲染 display: flex。)
	<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      baseStyles: {
        color: "red"
      },
      overridingStyles: {
        fontSize: '50px'
      }
    };
  },
};
</script>

<style scoped>
</style>

原博文vue中Class 与 Style 绑定_浪在前端的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值