Preface
In actual development, we often encounter dynamic binding of class, and common situations may be:
- Render different class styles according to different return values (that is, two or more dynamic classes are selected to use);
- When the UI is not determined for the style of a certain module during design, we will write this module (given the basic style);
- UI has many styles for a certain module when designing it, but it is not sure whether to use it all (the basic style is given).
In view of these three common situations, we can already choose these three common methods of dynamic loading cals when writing page styles.
1. Dynamically select class style (object addition: scenario 1)
<template> <div> <div class="basic" :class="classObj">Select Add Style</div> <div style="display: flex; flex-direction: column;"> <button style="width: 200px;" @click="chooseClass">Select Addcs_class1kind</button> <button class="btn" @click="chooseClass3">Select Addcs_class3kind</button> </div> </div> </template> <script> export default{ data() { return { classObj:{ cs_class1:false, cs_class3:false, }, } }, methods:{ chooseClass(){ .cs_class1=true .cs_class3=false }, chooseClass3(){ .cs_class1=false .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. Dynamically add a class style (string add: scenario 2)
<template> <div> <div class="basic" :class="boxrudius">Add a dynamic style</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. Dynamically add multiple class styles (array addition: scenario three)
<template> <div> <div class="basic" :class="classArr">Add multiple dynamic styles</div> <button class="btn" @click="addClassArr">Dynamically add multipleclasskind</button> </div> </template> <script> export default{ data() { return { classArr:[], } }, methods:{ addClassArr(){ =['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>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.