TL;DR
In this article, you’ll discover the power of Vue.js bind directives and its use cases in a cryptocurrency app. It is perfectly suited for all Vue Js and Javascript developers at every level.
Prerequisites
To fully understand this tutorial, you need to have at minimum:
A very basic knowledge of Vue.js.
A good understanding of Css and Descendant Selectors in Css.
If you have these, then by the end of this article, you will be able to write simple, interactive, and functional conditions using the Vue.js bind directive; and most importantly, how to use Vue.js bind directive for reactivity on application.
Introduction to Vue.Js Directives
In Vue.Js, directives are shortcuts used to add functionality to DOM elements. They specifically target, change, and make elements do more within the DOM.
While several directives improve the general functionality of a Vue web application, this tutorial will focus on a type of directive called the v-bind directive.
What is the Vue Bind directive?
When building web applications, certain HTML attributes (like src, href, class, etc.) can load by default, or they could be as a result of the conditions set by the developer.
Little user interactions, like clicking, can dynamically change some parts of the HTML to show different content, and these are crucial for improving User Experience(UX) in web and mobile applications, whether in a Social networking application, Web3 application, AI powered application, and many others.
For more context on these little interactions, let’s consider two instances using a man we’ll call “Dan”:
The first is Dan getting into a social app and searching for a profile. If the profile is online, he sees a green dot next to the name to show the profile is “active”; otherwise, he sees a red one(inactive).
The second is Dan in the process of ordering a shoe online. On the product description page, he finds two available sizes for the shoes he’s interested in. If sizes 14 and 18 are available, and he clicks on one, there would be an indication on the website that the size was selected, for this, by changing the button color to green (or another noticeable color).
Actions like these during development, would require a large chunk of code mostly composed of several CSS styles and traditional vanilla JavaScript or other framework conditions. This already seems like a stretch, especially considering how simple the functionality sounds.
Luckily, when building this reactivity, developers can use Vue.js to make the code easier to read, write, and understand with the v-bind directive.
To ‘bind’ in general terms, means to connect or attach two things together. This is a solid foundation to understanding what the V-bind directive does. It is a type of Vue.js directive that is attached to our HTML via a special token for the purpose of adding styling and functionality to DOM elements.
Its goal is not to change how the code works but to simplify the expression, and make it more readable and easier to manage, especially for larger projects.
They are specifically used for binding styles, classes, attributes, props etc.
There are two commonly used v-bind directives. They Include:
- The v-bind:style directive, and
- The v-bind:class directive.
Since this is the first part of a two-part article, our only focus here will be breaking down the v-bind:style directive.
We will take it step by step, from very basic and static syntax to more complex syntax and in every example of this first part article, we will be using iterations of the cryptocurrency application I’ve prebuilt as a reference.
This approach is intended to make it easier for you to understand, no matter what level you are.
If you happen to be more interested in the codes, then you can head to my github repository here:
Alex Dunia’s github repository
What is the V-bind:style directive ?
V-bind:style directives are special tokens that are used to add styles directly on the html.
It’s as easy as it sounds, they are simply written directly on our HTML, and can be done in three ways:
- The String Syntax
- The Object Syntax
- The Array Syntax.
The String Syntax
If you’ve written CSS, then you should be used to this syntax:
+$400
// The outcome of the code would be a red color on our page.
This pattern of CSS is known as inline css styles, and they allow us to create styles directly within the HTML tag.
As simple as it is, It is not far off from the work the string syntax does.
The v-bind:style string syntax allows you to apply styles as a single string, just like inline CSS.
Here is the app we will be working with, along with a link to view the project live:
(https://alexdunia.github.io/spendcryptai/)
There are two key things to note here:
- The Balance
- The Transaction History.
The balance is $400, and it’s colored green. We can write this with the v-bind:style string syntax.
But first, we will start by declaring a ref that contains the actual value of the account balance:
Next, we will add the style using the v-bind:style string syntax.
${{ accountBalance }}
In the code above, we have a span where our directive sits.
syntax allows us to bind a dynamic value to an HTML attribute. In simpler terms, it allows us to change the CSS styles of an HTML element based on data inside our Vue component (in our case, the accountBalance). We are attaching (binding) dynamic styles (CSS) to the element, and after the connection is made, we can then manipulate the HTML styling however we choose.
Since we are using the string syntax, we will add a string inside our quotes, and write our styling inside it, just like we did with the inline css:
${{ accountBalance }}
With this, our application is set, and our $400 balance is now coloured Green.
This look great, but we want some styling reactivity based on the wallet balance,
That is:
If the wallet balance is $1, or more than $1, the text will be Green (Sufficient Balance).
If the wallet balance is less than $1, then the text will be Red (Insufficient Balance):
These will serve as clear visual cues that will help users (Like Dan from earlier) be more intuitive about the status of their account. Hence, if Dan is the owner of the wallet, he can easily know if his balance is sufficient or insufficient without necessarily paying too much attention to the actual figures.
Traditionally, to achieve this with Vue.JS, it has to be written in an if-else statement in the script section of our Vue Js code, followed by a mount, for when the app is loaded.
This already seems hectic, and would lead to a chunk of code.
The string syntax will serve as the syntactic sugar that will allow us to achieve this with fewer lines of code.
The first step is to not make any changes to the accountBalance.
const accountBalance = ref(400)
Note: This balance can either be Positive values (e.g., 400) or negative values (e.g., -400).
Next, we want to be able to monitor the number.
At the moment, it is $400, but if it drops below $0, we need the app to change the color accordingly. This can be achieved with a condition created using a ternary operator.
The Vue.JS bind directive allows us to write a ternary operator inside our v-bind:style directive so we can set our conditions inside the string in our markup:
${{ accountBalance }}
Note: If it was the array syntax, we would have an array replacing the strings and If it was the Object syntax, we would have an object.
As seen inside the string:
accountBalance > 0 ? 'color: #00ff00' : 'color: #ff0000'
What this condition set with a ternary operator means is If the accountBalance is greater than zero (written in the code as accountBalance > 0), then (written on the code as a question mark ‘?’), we set the CSS styling to green*(with the color code of ‘#00ff00’); otherwise (on the code as a colon ‘:’), we set the color to red(with the color code of ‘#ff0000’*).
With this implementation, the account balance will be displayed in green. However, if the balance is manually changed to a value below zero, the text will automatically update to red.
It’s important to note that any CSS style properties (such as background-color, font-size, font-weight, etc.) can be applied directly using Vue.js’s v-bind:style directive, Not just the color property used in our example. The same way we added one style property, we can also update multiple styles in response to data changes.
In situations like this where you need to add multiple CSS styles at once, you write them in a single string inside the v-bind:style directive and separate each styling with a semicolon.
Like this:
${{ accountBalance }}
Note: The Object syntax and Array Syntax for the style directives are better alternatives to go around situations like this, and the v-bind:class directive can be used to make the aforementioned more readable.
Next, we want to build the transaction history section of our web application.
Our credit notification features a green line on the left side, while our debit notification has a red line on the left side.
In order to achieve this we must first store the transactions in an array. ]
Note: In a real-life scenario, we would fetch transactions from the backend using a GET request. If you intend to do this, simply add a GET request and store the response in the transactions array to achieve the same results.
In the amount field of the transactions array, we have positive and negative values.
Positive amount values (e.g., 10) represent credits.
Negative amount values (e.g., -10) represent debits.
This is how we would be able to monitor our application to tell if a transaction is debit or credit, and in the same way, give us the needed color.
Following this, we will add some lines of code:
{{ transaction.amount > 0 ? 'Account Credited from ' : 'Account Debited for ' }} {{ transaction.id }}
Here, we first make a class and a transaction history heading, then, we loop through the transactions array to display all transaction values on our web page.
Then for our class called ‘tracker-item’, we access the transaction amount using transaction.amount, check if it is greater than zero, and use the style directive to apply the styling directly on our markup.
Based on the same condition, we also add the text "Account credited from" or "Account debited from." on our P tag.
Now, you should get the appropriate colors that indicate the credit and debit section.
It only gets better from here because Vue.JS makes the code cleaner and easier to write with their shorthand.
Rather than writing v-bind:style, you just write :style, and it performs the same function:
{{ '{{' }} transaction.amount > 0 ? 'Account Credited from ' : 'Account Debited for ' {{ '}}' }} {{ '{{' }} transaction.id {{ '}}' }}
With simple and very little code, we have been able to achieve a lot compared to vanilla Javascript and other Javascript frameworks.
As mentioned earlier, the v-bind:style also supports Object Syntax and the Array Syntax.
V-bind:style Object Syntax
The v-bind:style Object Syntax allows you to apply styles as Javascript objects.
It serves the same purpose of styling, but compared to the string syntax, is better for cases where we add multiple style properties dynamically.
Like every object in traditional programming, it is wrapped in curly braces, and contains key-value pairs.
For instance, in Javascript, an object will look like this:
let family = {
father: "David",
mother: "Esther",
fathersAge: 40
};
father, mother, and fathersAge are keys.
"David", "Esther", and 40 are the values associated with each key.
The object syntax follows this template, especially in terms of key-value pairs. The major difference however, is the keys are CSS properties and the values will be the value associated with the CSS property.
Here’s a very basic example of the v-bind:Style Object Syntax that gives more context to our explanation:
Note: To properly follow along, you will have to indent the previous string syntax and copy or write this on your code editor.
${{ accountBalance }}
Inside the curly braces {}, we define a JavaScript object where the key value pairs follow CSS rules;
The key is the CSS property called ‘color’.
The value is the value of the associated CSS property. The value could either be the hex value, RGB values, or named colors.
We should see a green balance now.
Next, we want the styles to change depending on the wallet balance, so, our object syntax would look like this:
${{ accountBalance }}
The major difference between setting conditions here, and with the string syntax, is how we set our conditions.
In the object syntax, conditions are defined directly within the key-value pairs, where the key represents the CSS property (such as color), and the value is dynamically assigned based on the condition.
If the accountBalance is greater than 0, the color will be green (#00ff00). Otherwise, it will be red (#ff0000).
For cases where we want to add multiple styling, we would easily separate it via a comma:
${{ accountBalance }}
Where the newly added style is the font size, and it’s set on the same condition.
In the V-bind Array Syntax, we can pass in arrays directly on our markup, and inside the arrays would have the styles we need for our web application.
Let's go back to our application, and assume we do not want to place a condition on the account balance. We just want a green color; this is how we would achieve that using the array syntax,
We would declare a REF, and inside it an object, where we want some static colors:
const accountBalanceColor = ref({
color: '#00ff00',
fontSize: '20px',
})
Note: To follow along with this, you would again need to remove all styles for the account balance, along with the conditions previously set.
Next, we want to add this to our markup, and It’s as simple as writing the array directly inside the style directive:
${{ accountBalance}}
With that, we have a green color.
In cases where we need to have a condition, then we place the ternary operator inside the array, and create a ref that houses the color of the insufficient balance.
${{ accountBalance }}
This code follows the same logic as previous examples, where we conditionally apply styles based on the accountBalance. The difference here is that we are using an array syntax to apply styles, and the outcome of our condition (accountBalance > 0) determines which style object (either accountBalanceColor or insufficientBalance) is used. These style objects are defined in the block.
const insufficientBalance = ref({
color: '#ff0000',
fontSize: '20px',
})
Then, if we need to add another condition, we simply add a comma after the first like this:
<span :style="[
accountBalance > 0 ? accountBalanceColor : insufficientBalance,
accountBalance > 1000 ? highBalanceColor : {}
]">
${{ accountBalance }}
</span>
And that’s all it takes.
Conclusion
In this guide, we have walked through the steps of using Vue.js Directives to add functionality to DOM elements, and how faster it is.
While we’ve explored a couple of features, we have barely scratched the surface of the countless use cases for using Vue.Js Directives, ranging from building interactive AI interfaces, to building interfaces across other niches.
Hopefully, this guide gives you a general overview of the possibilities of the bind directives.