How to bind class attributes
1. Binding multiple class es for elements through arrays
1 <style> 2 .red { 3 color:red; 4 /*color:#ff8800;*/ 5 } 6 .bg { 7 background: #000; 8 /*background: green;*/ 9 } 10 </style> 11 12 13 window.onload = function(){ 14 var c = new Vue({ 15 el : '#box', 16 data : { 17 red_color : 'red', 18 bg_color : 'bg' 19 } 20 }); 21 } 22 23 24 25 <div id="box"> 26 <span :class="[red_color,bg_color]">this is a test string</span> 27 </div>
For example, span binds two classes. By setting the values of red_color and bg_color, the corresponding class class name is found.
2. Use the corresponding class class name by controlling true or false of the class. True: Use the class, false: Do not use the class
1 <style> 2 .red { 3 color:red; 4 } 5 .bg { 6 background: #000; 7 } 8 </style> 9 10 window.onload = function(){ 11 var c = new Vue({ 12 el : '#box', 13 data : { 14 } 15 }); 16 } 17 18 <div id="box"> 19 <span :class="{red:true,bg:true}">this is a test string</span> 20 </div> 21
3. This approach is similar to the second one, except that the true/false state of the class is replaced by a variable.
1 <style> 2 .red { 3 color:red; 4 } 5 .bg { 6 background: #000; 7 } 8 </style> 9 10 window.onload = function(){ 11 var c = new Vue({ 12 el : '#box', 13 data : { 14 r : true, 15 b : false 16 } 17 }); 18 } 19 20 <div id="box"> 21 <span :class="{red:r,bg:b}">this is a test string</span> 22 </div>
4. Binding the entire json object for the class attribute
1 <style> 2 .red { 3 color:red; 4 } 5 .bg { 6 background: #000; 7 } 8 </style> 9 10 window.onload = function(){ 11 var c = new Vue({ 12 el : '#box', 13 data : { 14 json : { 15 red : true, 16 bg : false 17 } 18 } 19 }); 20 } 21 22 23 <div id="box"> 24 <span :class="json">this is a test string</span> 25 </div>
2. Multiple ways to bind style interline styles
1. Write directly between lines using json format
1 window.onload = function(){
2 var c = new Vue({
3 el : '#box',
4 });
5 }
6
7 <div id="box">
8 <span :style="{color:'red',background:'#000'}">this is a test string</span>
9 </div>
2. Bind an object in data as an item in an array to style
1 window.onload = function(){
2 var c = new Vue({
3 el : '#box',
4 data : {
5 c : {
6 color : 'green'
7 }
8 }
9 });
10 }
11
12 <div id="box">
13 <span :style="[c]">this is a test string</span>
14 </div>
3. It's similar to the way above, except that there are multiple objects for the array.
1 window.onload = function(){
2 var c = new Vue({
3 el : '#box',
4 data : {
5 c : {
6 color : 'green'
7 },
8 b : {
9 background : '#ff8800'
10 }
11 }
12 });
13 }
1 <div id="box"> 2 <span :style="[c,b]">this is a test string</span> 3 </div>
4. Binding an object in data directly to style
1 window.onload = function(){
2 var c = new Vue({
3 el : '#box',
4 data : {
5 a : {
6 color:'yellow',
7 background : '#000'
8 }
9 }
10 });
11 }
1 <div id="box"> 2 <span :style="a">this is a test string</span> 3 </div>