VUE 动态绑定class类的三种常用方法及适用场景

前言

在实际开发中,我们会经常遇到动态绑定class的情况,常见的情况可能有:1,根据不同的返回值渲染不同的class样式(也就是两个及两个以上的动态class选择使用);2,UI在设计时对于某个模块的样式没有确定下来的时候我们去写这个模块(给了基础样式);3,UI在设计对于某个模块的样式有很多样子,但不确定用是否全部使用时(给了基础样式)。针对这三种常见的情况我们在写页面样式时可已选择这三种常见的动态加载calss的方法。

一:动态选择class样式(对象添加:情景一)

<template>
 <div>
    <div class="basic" :class="classObj">选择添加样式</div>
	<div style="display: flex; flex-direction: column;">
	  <button  style="width: 200px;"  @click="chooseClass">选择添加cs_class1类</button>
	  <button  class="btn"  @click="chooseClass3">选择添加cs_class3类</button>
    </div>
 </div>
</template>
<script>
	export default{
		data() {
			return {
				classObj:{
					cs_class1:false,
					cs_class3:false,
				},
			}
		},
		methods:{
			chooseClass(){
				this.classObj.cs_class1=true
				this.classObj.cs_class3=false
			},
			chooseClass3(){
				this.classObj.cs_class1=false
				this.classObj.cs_class3=true
			}
		}
	}
</script>

<style>
	.basic{
		display: flex;
		align-items: center;
		justify-content: center;
		background: pink;
		width: 200px;
		height: 100px;
	}
	.btn{
		width: 200px;
		margin-bottom: 20px;
	}
	.box_rudis{
		border-radius: 30px;
	}
	.cs_class1{
		color: red;
	}
	.cs_class2{
		border:2px solid #0000FF
	}
	.cs_class3{
		background: yellow;
	}
</style>

二:动态添加一个class样式(字符串添加:情景二)

<template>
	<div>
		<div class="basic" :class="boxrudius">添加一个动态样式</div>
	</div>	
</template>
<script>
	export default{
		data() {
			return {
				boxrudius:'box_rudis',	
			}
		},
	}
</script>
<style>
	.basic{
		display: flex;
		align-items: center;
		justify-content: center;
		background: pink;
		width: 200px;
		height: 100px;
	}
	.box_rudis{
		border-radius: 30px;
	}
</style>

三:动态添加多个class样式(数组添加:情景三)

<template>
	<div>
		<div class="basic" :class="classArr">添加多个动态样式</div>
		<button class="btn" @click="addClassArr">动态添加多个class类</button>
	</div>	
</template>
<script>
	export default{
		data() {
			return {
				classArr:[],
			}
		},
		methods:{
			addClassArr(){
				this.classArr=['cs_class1','cs_class2','cs_class3']
			},
		}
	}
</script>

<style>
	.basic{
		display: flex;
		align-items: center;
		justify-content: center;
		background: pink;
		width: 200px;
		height: 100px;
	}
	.btn{
		width: 200px;
		margin-bottom: 20px;
	}
	.box_rudis{
		border-radius: 30px;
	}
	.cs_class1{
		color: red;
	}
	.cs_class2{
		border:2px solid #0000FF
	}
	.cs_class3{
		background: yellow;
	}
</style>
上一篇:go语言操作mysql数据库


下一篇:第六篇:vue.js模板语法(,属性,指令,参数)