当前位置: 代码网 > it编程>前端脚本>Vue.js > VUE动态绑定class类的三种常用方式及适用场景详解

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

2025年02月13日 Vue.js 我要评论
前言在实际开发中,我们会经常遇到动态绑定class的情况,常见的情况可能有:根据不同的返回值渲染不同的class样式(也就是两个及两个以上的动态class选择使用);ui在设计时对于某个模块的样式没有

前言

在实际开发中,我们会经常遇到动态绑定class的情况,常见的情况可能有:

  1. 根据不同的返回值渲染不同的class样式(也就是两个及两个以上的动态class选择使用);
  2. ui在设计时对于某个模块的样式没有确定下来的时候我们去写这个模块(给了基础样式);
  3. ui在设计对于某个模块的样式有很多样子,但不确定用是否全部使用时(给了基础样式)。

针对这三种常见的情况我们在写页面样式时可已选择这三种常见的动态加载calss的方法。

1.动态选择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>

2.动态添加一个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>

3.动态添加多个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>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com