Common binding styles
Write the style directly in style, then use class=” defined style name “where necessary
<template> <div class="green"> Hello vue </div> </template> <script> export default {} </script> <style lang=" SCSS" scoped> .green{ width: 100px; height: 50px; background: rgb(212, 111, 16); } </style>Copy the code
The following figure is displayed after running
Bind dynamic styles
Define an attribute in data, then use V-bind :class=” attribute name “where needed or use the syntactic sugar shorthand :class=” attribute name”
<template>
<div :class="myClass">
你好 vue
</div>
</template>
<script>
export default {
data(){
return{
myClass:"green",
}
}
}
</script>
<style lang="scss" scoped>
.green{
width: 100px;
height: 50px;
background:green;
}
</style>
Copy the code
3. Bind multiple attribute classes
Define in data whether the property is displayed, that is, bool, when it is true. Use the key-value form where you want it :class=”{‘active’:isActive,’green’:isGreen}” This means that the active style is displayed when isActive is true, enclosed in braces, and multiple attributes separated by commas
<template> <div :class="{'active':isActive,'green':isGreen}"> </div> </ script> export default { data(){ return{ myClass:"green", isActive:true, isGreen:true } } } </script> <style lang="scss" scoped> .active{ display: block; font-size: 30px; color:red; } .green{ width: 200px; height: 50px; background:green; } </style>Copy the code
The effect is shown as follows. When both are true, the style takes effect
4. Mixed writing
It is also possible to use the normal script in conjunction with the binding dynamic property script, as shown below
<template> <div class="green" :class="{'active':isActive}"> hello vue </div> </template>Copy the code
It looks like the picture
5. Use array binding
Bind the defined style to the properties in data, and then use :class=”[]” to bind multiple properties separated by commas
<template> <div :class="[isActive,isGreen]"> Hello vue </div> </template> <script> export default {data(){return{ isActive:"active", isGreen:"green" } } } </script> <style lang="scss" scoped> .active{ display: block; font-size: 30px; color:red; } .green{ width: 200px; height: 50px; background:green; } </style>Copy the code
Array and ternary operators are used to determine the desired class
<div :class="[isActive?'active':'green']">
Copy the code
Interpretation: Active style is displayed when isActive is true, green style is displayed when false
Array objects combined with dynamic judgment
<div :class="[{active:isActive},'green']">
Copy the code
Interpretation: Show green, and the active style takes effect when isActive is true
Determine whether to bind an active style
<div :class="{'active':isActive==1}">
Copy the code
Interpretation: If isActive=1, show the active style