前言
在实际开发中,我们会经常遇到动态绑定class的情况,常见的情况可能有:
- 根据不同的返回值渲染不同的class样式(也就是两个及两个以上的动态class选择使用);
- ui在设计时对于某个模块的样式没有确定下来的时候我们去写这个模块(给了基础样式);
- 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>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论