Vue.js样式绑定

Vue.js class

class 属性绑定

可以为 v-bind:class 设置一个对象,从而动态的切换 class

<style>
	.active {
		width: 100px;
		height: 100px;
		background: green;
	}
</style>

将 isActive 设置为 true 显示了一个绿色的 div 块,如果设置为 false 则不显示

<div id="app">
  <div v-bind:class="{ 'active': isActive }"></div>
</div>

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

可以在对象中传入更多属性用来动态切换多个 class

text-danger 类背景颜色覆盖了 active 类的背景色

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

可以直接绑定数据里的一个对象

<style>
.active {
	width: 100px;
	height: 100px;
	background: green;
}
.text-danger {
	background: red;
}
</style>
<div id="app">
  <div v-bind:class="classObject"></div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
		    classObject: {
		      active: true,
		      'text-danger': true
		    }
	  }
	})
</script>

可以在这里绑定返回对象的计算属性

<style>
.base {
  width: 100px;
  height: 100px;
}

.active {
  background: green;
}

.text-danger {
  background: red;
}
</style>
<div id="app">
  <div v-bind:class="classObject"></div>
</div>
<script>
	new Vue({
	  el: '#app',
	  data: {
	    isActive: true,
	    error: {
	      value: true,
	      type: 'fatal'
	    }
	  },
	  computed: {
	    classObject: function () {
	       return {
		  		base: true,
		        active: this.isActive && !this.error.value,
		        'text-danger': this.error.value && this.error.type === 'fatal',
	      }
	    }
	  }
	})
</script>

数组语法

可以把一个数组传给 v-bind:class

<div id="app">
	<div v-bind:class="[activeClass, errorClass]"></div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
	    activeClass: 'active',
	    errorClass: 'text-danger'
	  }
	})
</script>

三元表达式来切换列表中的 class

div id="app">
	<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
	    isActive: true,
		activeClass: 'active',
	    errorClass: 'text-danger'
	  }
	})
</script>

Vue.js style(内联样式)

在 v-bind:style 直接设置样式

<div id="app">
	<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">菜鸟教程</div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
	    activeColor: 'green',
		fontSize: 30
	  }
	})
</script>

直接绑定到一个样式对象,让模板更清晰

<div id="app">
  <div v-bind:style="styleObject">菜鸟教程</div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
	    styleObject: {
	      color: 'green',
	      fontSize: '30px'
	    }
	  }
	})
</script>

v-bind:style 可以使用数组将多个样式对象应用到一个元素上

<div id="app">
  <div v-bind:style="[baseStyles, overridingStyles]">菜鸟教程</div>
</div>

<script>
	new Vue({
	  el: '#app',
	  data: {
	    baseStyles: {
	      color: 'green',
	      fontSize: '30px'
	    },
		overridingStyles: {
	      'font-weight': 'bold'
	    }
	  }
	})
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44141284/article/details/130646757