跟着网上学Vue之样式绑定

class属性

从某鸟教程里面发现一段代码,容易搞混
在style中添加的样式:

.active {
	width: 100px;
	height: 100px;
	background: green;
}
.text-danger {
	background: red;
}

在body中添加的代码:

<div id="app">
  <div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
  </div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
	hasError: true
  }
})
</script>

结果图:
在这里插入图片描述

  • 一开始很纠结为什么是红色覆盖绿色,然后试了很多方法,突然想起来是“就近原则”,然后我就试着把style的样式顺序换一下,结果成功了。(新手要注意了

此外,在通过vue设置class的时候,还可以通过对象传值
某鸟教程说的:

<div v-bind:class="classObject"></div>
new Vue({
  el: '#app',
  data: {
    classObject: {
      active: true,
      'text-danger': true
    }
  }
})

数组设置class

//body中
<div v-bind:class="[activeClass, errorClass]"></div>
//script中
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})

三元式设置class

//body中
<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
//script中
new Vue({
  el: '#app',
  data: {
    isActive: true,
	activeClass: 'active',
    errorClass: 'text-danger'
  }
})

设置style

  1. 普通设置style
//body内
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">教程</div>

//script内
new Vue({
  el: '#app',
  data: {
    activeColor: 'green',
	fontSize: 30
  }
})
  1. 单个样式对象设置style
//body内
 <div v-bind:style="styleObject">教程</div>
//script内
new Vue({
  el: '#app',
  data: {
    styleObject: {
      color: 'green',
      fontSize: '30px'
    }
  }
})
  1. 多个样式对象设置style
//body内
 <div v-bind:style="[baseStyles, overridingStyles]">教程</div>
 //script内
 new Vue({
  el: '#app',
  data: {
    baseStyles: {
      color: 'green',
      fontSize: '30px'
    },
	overridingStyles: {
      'font-weight': 'bold'
    }
  }
})

注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值