Vue.js Chronicles (Part II): Directives, Modifiers, Computed Properties, Watchers
Topics: Directives - [v-cloak, v-model, v-html], Modifiers, Computed Properties, Watchers
Introduction
In the previous article we built our first Vue application and also learnt about data function, methods option and took a deep dive to understand how proxy getters and setters work when we try to access or modify the properties defined inside the Vue app.
This article will introduce you to Directives, Modifiers , Computed Properties and Watchers.
Let’s begin!
Directives
Directives in Vue.js are special tokens in the markup that tell the library to do something to a DOM element. They are prefixed with v-
to indicate that they are special attributes provided by Vue. Directives are used to manipulate the DOM by binding data to the template, rendering content conditionally, or listening to events.
Here are some common Vue directives and their uses, along with examples:
v-cloak
The v-cloak
directive in Vue.js is a special directive used to prevent the flash of uncompiled template (also known as FOUC - Flash of Unstyled Content) before the Vue instance is fully initialized.
When you use Vue, there's a brief moment where the Vue template is visible in its raw form (with {{ }}
bindings) before Vue finishes compiling it. This can happen, for example, if the JavaScript file that initializes Vue is loaded after the HTML has been rendered. Generally, we do not see it happen if our internet speed is high but if it’s slow, you can see this happen in your browser.
How v-cloak
Works
Purpose:
v-cloak
is used to hide the raw template content until Vue's compilation is complete.How it Works: You can add
v-cloak
to an element, and then use CSS to hide that element until Vue has fully initialized. Once Vue is ready, it removes thev-cloak
attribute, making the content visible.
Example
Explanation
v-cloak
Directive: Thev-cloak
directive is applied to thediv
element that contains Vue’s template.CSS Rule
[v-cloak] { display: none; }
: This CSS rule hides any element with thev-cloak
attribute.Vue Compilation: When Vue is initialized and the data bindings are compiled, Vue automatically removes the
v-cloak
attribute. Once the attribute is removed, the CSS rule no longer applies, and the content becomes visible.
Use Case
The v-cloak
directive is particularly useful in scenarios where:
JavaScript files are loaded asynchronously, and there's a chance that users might see the uncompiled template before Vue is ready.
You want to ensure that your Vue template does not display raw bindings to users while the Vue instance is initializing.
v-model
The v-model
directive in Vue.js is used for creating two-way data bindings on form input elements, like text inputs, checkboxes, and radio buttons. It keeps the DOM (Document Object Model) in sync with the Vue instance data, allowing for seamless updates between the user interface and the data model.
How v-model
Works?
When you use v-model
on an input element, Vue automatically binds the element's value to a data property on the Vue instance. As a result, any changes to the input will immediately update the data property, and any changes to the data property will update the input's value.
Basic Usage
What we have done is: Two Way Binding!
Two-way data binding in Vue.js refers to the synchronization between the data model (JavaScript data) and the view (HTML DOM). This means that changes to the UI elements (like form inputs) automatically update the data model, and changes to the data model automatically update the UI elements.
In Vue.js, two-way binding is typically achieved using the v-model directive.
How Two-Way Binding Works?
When you use the v-model
directive on an input element, it binds the element's value to a data property in the Vue instance. This binding ensures that any updates to the input field automatically change the corresponding data property, and any changes to the data property reflect immediately in the input field.
v-html
In Vue.js, the v-html
directive allows you to dynamically update the inner HTML of an element. This can be useful for rendering HTML content that is dynamically generated or fetched from a server. However, it is essential to use v-html
cautiously due to potential security risks, particularly Cross-Site Scripting (XSS) attacks.
Key Points about v-html
Expects: A string containing HTML content.
HTML Content: The content will be inserted as plain HTML. Vue’s template syntax will not be processed within
v-html
.Security: Only use
v-html
with trusted content to avoid XSS vulnerabilities.Scoped Styles: In Single-File Components (SFCs), scoped styles will not apply to content inserted with
v-html
.
Explanation
Initial HTML Content
The
<div v-html="htmlContent"></div>
element in the template is used to render HTML content specified by thehtmlContent
data property.Updating HTML Content
The
updateHtml
method modifies thehtmlContent
property, which in turn updates the HTML content displayed in the<div>
element.Security Warning
Ensure that the content being inserted via
v-html
is from a trusted source. Dynamically injecting HTML can expose your application to security risks, such as XSS attacks, if the content includes untrusted or user-generated HTML.
What are Modifiers in Directives?
In Vue.js, modifiers are special suffixes denoted by a dot (.
) that you can add to directives to change their behavior. Modifiers are used with various Vue directives, such as v-on
, v-model
, and v-bind
, to apply specific functionality or constraints. They make it easy to implement common patterns like stopping event propagation, preventing default behavior, or transforming data before binding.
I have not yet covered the v-on and the v-bind directives. However, we have discussed in detail the v-model directive. Let us start looking at the modifiers for v-model directive.
Modifiers in v-model
In Vue.js, the v-model
directive provides a convenient way to create two-way data bindings on form inputs, textareas, and select elements. Modifiers can be added to v-model
to fine-tune how this binding works. There are three common v-model
modifiers:
.lazy
: Updates the data only when thechange
event occurs, instead of on each input event..trim
: Automatically trims any leading or trailing whitespace from the input value..number
: Automatically converts the input value to a number.
Detailed Examples
Let's explore each modifier with examples.
1. .lazy
Modifier
By default, v-model
syncs the input data on every input
event. With the .lazy
modifier, the data is only updated when the change
event is triggered (when the input loses focus).
2. .trim
Modifier
The .trim
modifier automatically removes any whitespace from both ends of the input value.
3. .number
Modifier
The .number
modifier automatically converts the input value to a number (note that when the user inputs a particular numeric value, the input is always taken as a string!). This is especially useful for numeric input fields.
Combining Modifiers
Modifiers can be combined to achieve more specific behavior. For example:
Computed Properties
Computed properties in Vue.js are a powerful feature that allows you to derive and manipulate data based on other data properties. Think of them as formulas in a spreadsheet that automatically recalculate when the data they depend on changes. They provide a way to create dynamic data without manually handling complex logic every time you need it.
Understanding Computed Properties with a Real-World Example
Imagine you’re running a bakery. You sell cakes and have the following data:
The base price of a cake.
The number of cakes a customer orders.
You want to calculate the total price every time a customer changes the quantity. While you could do this manually every time the quantity changes, it would be tedious. Instead, you can use a computed property.
In the context of Vue.js, this might look like:
and the corresponding .html file as:
The Bakery Example Explained
In the example above:
Data properties (
basePrice
andquantity
): These are like your ingredients. They’re the basic values you start with.Computed property (
totalPrice
): This is your recipe. It takes the base ingredients (data) and produces a final product (total price).
The computed property totalPrice
is automatically recalculated whenever either basePrice
or quantity
changes. Vue.js takes care of this behind the scenes, so you don’t need to manually trigger the calculation every time something changes.
In the bakery example, if a customer decides to order more cakes, Vue will automatically update the total price without you needing to do any extra work.
Why Not Use Methods Instead?
You might wonder, “Why not just use a method to calculate the total price?” You could, but computed properties have a key advantage: caching.
When a computed property is accessed, it’s only recalculated if the data it depends on has changed. If the data hasn't changed, Vue returns the last calculated value. This makes computed properties more efficient than methods for many scenarios.
Imagine our bakery is very busy. If multiple customers are looking at the total price, you don’t want to recalculate it every time they glance at it. With a computed property, Vue only recalculates the price when something like the quantity or base price changes. Otherwise, it simply shows the already calculated value, saving time and resources.
Let Us Take A More Complex Example: Fitness Tracker
Let’s extend this with a fitness tracker example. Suppose you’re building an app that tracks how many steps someone takes each day and converts those steps into miles. The number of steps is your data property, while the number of miles is a computed property.
and the HTML file:
Here:
Steps are the raw data (like the number of cakes ordered).
Miles are derived from the steps using the
miles
computed property (like calculating the total price).
When you update the number of steps, the miles
computed property automatically updates. You don’t need to worry about recalculating it manually every time.
Watchers
Watchers in Vue.js are like vigilant assistants that keep an eye on specific data properties and take action whenever those properties change. Unlike computed properties, which are primarily used for deriving values, watchers are all about executing custom logic when data changes. They’re perfect for scenarios where you need to do something specific in response to a change, like calling an API, performing a side effect, or updating another part of your application.
Understanding Watchers with a Practical Example
Let’s return to the bakery analogy. Imagine you have a bakery website where customers can input the number of cakes they want. As they increase the quantity, you want to immediately inform the bakery's staff to prepare those cakes.
You could manually monitor the quantity field, but Vue.js offers a more elegant solution: watchers.
Here’s how it might look in Vue.js:
The Bakery Example Explained
In this example:
Data property (
quantity
): This is the number of cakes the customer wants.Watcher (
quantity
): This is the vigilant assistant. Whenever thequantity
changes, the watcher springs into action.Methods (
notifyStaff
): This is where the custom logic happens. When the watcher detects a change, it triggers this method to notify the staff.
Every time the customer updates the quantity, the watcher logs the change and calls the notifyStaff
method. This method could be anything from alerting the staff to sending a message to the bakery’s inventory system.
Why Use Watchers?
Watchers are your go-to tool when you need to respond to changes in your data but don’t necessarily want to calculate or display a value. They’re useful for:
Asynchronous operations: Fetching data from an API when a certain piece of data changes.
Side effects: Performing an action like updating a UI element, sending analytics data, or saving to local storage.
Complex logic: When the logic you need to execute is too complex or involves multiple steps.
Another Example: Weather App
Imagine you’re building a weather app. You have a data property that stores the city name. Every time the user changes the city, you want to fetch the latest weather data from an API. Here’s how you’d use a watcher:
The Weather App Example Explained
Here:
City data: This is the city the user is interested in.
Watcher (
city
): Watches for changes to the city and fetches the latest weather data.Methods (
fetchWeather
): Handles the API call and updates the weather data.
When the user changes the city, the watcher detects this change, logs it, and then calls fetchWeather
to get the latest weather data. The watcher ensures that every time the city changes, your app fetches fresh information automatically.
Conclusion
In this article, we covered key Vue.js features like directives, computed properties, and watchers. We explored how v-cloak
, v-model
, and v-html
enhance your application by managing visibility, enabling two-way data binding, and safely injecting raw HTML. Computed properties simplify your code by automatically updating derived data, while watchers let you react to changes with custom logic.
These tools make Vue.js powerful and user-friendly, helping you build dynamic, responsive applications with ease. As you dive deeper, these features will prove essential in creating smooth, interactive user experiences.
Happy Coding in Vue.js!