Vue : v-bind directive

v-bind directive

Syntax

As mentioned Vue.js can dynamically generate HTML using one of the directives. To dynamically generate attributes of an HTML element, the “v-bind” directive is used.

v-bind:someHtmlAttribute = "dataProperty"

Using this directive, we can reactively associate the attribute value with a “data” object:

Example

<img v-bind: src = "imageSrc">
<a v-bind:href = "hreflink"> ... </a>
<div v-bind: title = "message"> ... </div>
<div v-bind: class = "letClass"> ... </div>
<div v-bind: style = "{color: red, min-width: width}"> ... </div>
 
<script>
new Vue ({
   el: '#example',
   data: {
     imageSrc: "https://www.alenibric.com.tr/images/somepicture.jpg",
     hreflink: "https://www.alenibric.com.tr",
     message: "Some message",
     letClass: "bold",
     width: "4rem",
     }
});
</script>

Shortened directive writing

This v-bind: directive has a short syntax represented by two points :

Example

<a :href="url">...</a>

v-bind:class

One of the more commonly used versions of this directive is “v-bind: class”, which allows the class to be dynamically added to the desired HTML element.

a) Simple syntax

With this syntax v-bind: class = ”classname” we bind the class name to the selected element.

Example

In this example, we will associate a CSS class name with a reactive variable named “color” using a directive v-bind: class = “color”:

HTML

<div class = "container text-center">
     <select id = "color" class = "custom-select" v-model = "color">
             <option disabled value = ""> Select the color of the square </option>
             <Option> red </ option>
             <Option> blue </ option>
             <Option> green </ option>
     </select>
     <div class = "box" in-bind: class = "color"> </div>
</div>

SCSS

.red {
  background: #ff0000;
}
.blue {
  background: #0000ff;
}
.purple {
  background: #7B1FA2;
}
.green {
  background: #4CAF50;
}
.container{
    padding: 2rem;
    display: flex;
    flex-direction: column;
}
.box {
  

Babel

let vm = new Vue({
  el: '.container',
  data: {
    color: ""
    }
});
Example

b) Object syntax

This syntax is based on an object whose key is the class name and the value is true or false.

<div v-bind: class = "{'className1': true, 'className2': false, 'className3': true}"> </div>

It should be emphasized that existing classes on the HTML element will not interfere with this dynamic addition of classes.

Example

This example shows one variation of the previous syntax when not using an inline object but the variable representing it. The following classes have been added to the result of this directive: “classname1” and “classname3” to the HTML element.

<div v-bind: class = "allClassElements"> </div>
data: {
     allClassElements:
         {
             'class1Name': true,
             'className2': false,
             'className3': true
         }
}

Example

HTML

<div class="container text-center">
    <div class="box" v-bind:class="{ 'red' : itisOK, 'blue' : !itisOK}"></div>
    <div class="box" v-bind:class="{ 'purple' : itisOK, 'green' : !itisOK }"></div>
    <button v-on:click="flipColor" class="btn btn-block btn-success">Change colors!</button>
</div>

SCSS

.red {
  background: #ff0000;
}
.blue {
  background: #0000ff;
}
.purple {
  background: #7B1FA2;
}
.green {
  background: #4CAF50;
}
.box {
  float: left;
  width: 50px;
  height: 50px;
  margin: 20px;
  border: 1px solid rgba(0, 0, 0, .2);
}

Babel

let vm = new Vue({
  el: '.container',
  data: {
    itisOK: true
  },
  methods: {
    flipColor: function() {
      this.itisOK= !this.itisOK;
    }
  }
});

Condition syntax object

Inline syntax can use inline conditional expressions:

<li v-for="page in totalPages" v-bind:class="{'page-item':true, 'active':(page === currentPage)}">

c) Array syntax

This syntax uses square brackets under double quotes, so we need to use single quotes or instead of a class name to use a variable name representing the class v-bind: class = “[variable, ‘class-name’]”

<div v-bind: class = "[className1, className2]">
 
<Script>
     let vm = new Vue ({
         el: '.container',
         data: {
             className1: 'class-1-name',
             className2: 'class-name-2'
         }
     });
</ Script>

Example

HTML

<div id="app">
  <h3>
  Toggling Classes with Array syntax
  </h3>
  <hr>
  <input type="checkbox" id="checkbox" v-model="isBold">Bold text
	<input type="checkbox" id="checkbox" v-model="isPlava">Blue Color
	<input type="checkbox" id="checkbox" v-model="isVeliki">Large and thin text
  <div>
    <h1 class="dimensions" v-bind:class="[{ 'podebljano':isBold,'plava':isPlava,'povecano':isVeliki}]">Some Text</h1>
  </div>
</div>

SCSS

#app {
	padding: 2rem;
	.dimensions {
  height: 90px;
  line-height: 90px;
  text-align: center;
	background-color: yellowgreen
	}
	.podebljano {
		font-weight : bold;
	}
	.plava {
		color: blue;
	}
	.povecano {
		font-size:60px;
		font-weight:400;
	}
}

Babel

var app = new Vue({
  el: '#app',
  data: {
    isBold: false,
    isPlava: false,
    isVeliki: false
  }
});

REMARK:
In array syntax, the order of classes in case of overlapping CSS properties is important. The value defined with the last class takes precedence. So in the previous example, although the bold option is selected, the Large and Thin Text option will override it because it is further down the line.

Conditional array syntax

If you want the desired class to appear conditional, we will achieve this by using a ternary expression:

Example

v-bind: class = "[ordinaryClass, (page === currentPage)? conditionalActiveClass: '']"

Example

HTML

<div class="container text-center">
    <div class="box" v-bind:class="[ color ?  'red' : 'blue' ]"></div>
    <div class="box" v-bind:class="[ color ?  'purple' : 'green' ]"></div>
    <button v-on:click="flipColor" class="btn btn-block btn-success">Change Colors!</button>
</div>

SCSS

.red {
  background: #ff0000;
}
.blue {
  background: #0000ff;
}
.purple {
  background: #7B1FA2;
}
.green {
  background: #4CAF50;
}
.box {
  float: left;
  width: 50px;
  height: 50px;
  margin: 20px;
  border: 1px solid rgba(0, 0, 0, .2);
}

Babel

new Vue({
  el: '.container',
  data: {
    color: true
  },
  methods: {
    flipColor: function() {
      this.color = !this.color;
    }
  }
});

d) Mixed syntax

Different syntaxes can be mixed, but in this case, the class name in the string must be in single quotes:

<div class = "box" v-bind: class = "[color, {itisbold: itisOK}, 'add-margin']">

Example

HTML

<div class="container text-center">
	<div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="" v-model="istinitost">Add Shadow
	</label>
</div>
	<select id="boja" class="custom-select" v-model="color">
			<option disabled value="">Select Color</option>
			<option>red</option>
			<option>blue</option>
			<option>green</option>
	</select>
	<div class="box" v-bind:class="[color, {shadow: istinitost}, 'add-margin']"></div>
</div>

SCSS

.red {
  background: #ff0000;
}
.blue {
  background: #0000ff;
}
.purple {
  background: #7B1FA2;
}
.green {
  background: #4CAF50;
}
.shadow{
	  box-shadow: 3px 3px 5px 6px #ccc;
}
.container{
	padding: 2rem;
	display: flex;
	flex-direction: column;
}
.box {
  width: 50px;
  height: 50px;
  
  border: 1px solid rgba(0, 0, 0, .2);
}
.add-margin{
	margin: 100px auto;
}

Babel

let vm = new Vue({
  el: '.container',
  data: {
    color: "",
		istinitost: false	
	}
});

v-bind:style

For inline adding styles to a single HTML element, the Vue.js v-bind: style directive is used. If necessary, this directive even adds the manufacturer’s CSS prefixes to the property (as an autoprefixer).
Inline associating style attributes with the v-bind: style directive uses object syntax. The CSS property name is used for the key and the CSS property value for the value. The key can be written in the form of a so-called. Dash-case syntax (but must be in single quotes because dash is not a valid value as a property name in JavaScript) or so-called “CamelCase” that the JavaScript compiler will evaluate in this “dash-case” syntax (eg font Size in font-size).

<div v-bind:style="{ 'background-color': activeColor, fontSize: fontSize + 'px' }"></div>
 
<script>
    let vm = new Vue({
        data: {
            activeColor: 'red',
            fontSize: 30
        }
    });
</script>

or put everything in an object:

<div v-bind:style="styleObject"></div>
 
<script>
let vm = new Vue({
    computed: {
        styleObject: function (){
            return  {
                 color: 'red',
                 fontSize: '13px'
            }
 
         }
    });
</script>

Example

HTML

<div id="app">
	<button class="btn-primary btn" v-on:click="velicinaFonta++">Increase font size</button>
	<button class="btn-danger btn" v-on:click="smanji">Decrease font size</button>
	<p v-bind:style="promenaFontaParagrafa">Font size is: {{ velicinaFonta }}px</p>
</div>

SCSS

button {
	width : 10rem;
	margin:1rem;
}
p{
	width:100%;
	text-align:center;
}
#app {
	padding:2rem;
	text-align: center;
}

Babel

var app = new Vue ({
	el: "#app",
	data: {
		velicinaFonta: 30
	},
	methods: {
		povecaj: function (){
				this.velicinaFonta++;
		},
		smanji: function (){
				this.velicinaFonta--;
		}
	},
	computed: {
		promenaFontaParagrafa: function (){
			return {
					fontSize: this.velicinaFonta + 'px'
			}
		}
	}
});
Increase Font
Decrease Font

A series of objects

Using this directive, we can also apply multiple style objects to the same element:

<div v-bind:style="[{color: 'red',fontSize: '15px'}, styleObjectB, styleObjectC]"></div>
 
<script>
    data: {
        sirina: 30px,
        styleObjectB: {
            fontSize: '50px'
        }
    },
    computed: {
       styleObjectC: function (){
            return {
                width: this.sirina + px
            }
        }
    }
</script>
Likes:
15 0
Views:
1753
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *