Vue Basics
Understanding Vue Instances:
Vue.js applications are built around Vue instances. In other words, it is a Vue object that was created using the constructor for Vue.
Each Vue instance has its own scope within which it manipulates elements in the DOM; this section is defined by an HTML element passed to el parameter when creating an instance.
The Vue instance also contains data, methods, computed properties and lifecycle hooks responsible for its appearance and behavior on the DOM element.
Example:
<div id="app">
{{ message }}
</div>
<script>
// Creating a Vue instance
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
</script>
For instance here we create a Vue instance associated with #app, that defines a message data property string “Hello, Vue!”.
This message will be displayed within the #app element.
Vue Directives:
These are some special attributes that are available in vue.js and are prefixed by v-.
They make the html dynamic by adding dynamic behavior to them. This includes events handling, dom manipulation etc.
Some of these directives include v-bind used for binding data to HTML attributes, v-model two ways of binding data, v-if conditional rendering and v-for for looping through arrays.
Example:
<div id="app">
<p v-if="showMessage">{{ message }}</p>
<input type="text" v-model="inputText">
<p>{{ inputText }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
showMessage: true,
message: 'Hello, Vue!',
inputText: ''
}
});
</script>
In above example, we conditionally render the <p> element containing the message based on the value of the showMessage data property.
We use v-model to bind the input field to the inputText data property, enabling two-way data binding.
Interpolation and Data Binding:
Vue.js interpolation and data binding enables you to change the content in HTML elements with its associated data properties.
Interpolation is performed using double curly braces {{}}, making it possible for the expressions within these brackets to be evaluated and substituted by their values.
Also, this involves a mechanism of data syncing between DOM and Vue instance which facilitates reactivity.
Example:
<div id="app">
<p>{{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
</script>
As in this case where the message data property is placed inside a <p> element, thus when we load this page in our browser we will see “Hello, Vue!” appearing as plain text.
In other words if the value of message changes from within the Vue object then the new value will be reflected automatically on the screen.