How to Conditionally Add an Attribute for an Element in VueJS?
Last Updated :
11 Sep, 2024
In VueJS, it's common to add attributes dynamically to HTML elements based on certain conditions. This allows for greater flexibility and control when rendering elements. Vue.js provides several ways to conditionally add or remove attributes depending on data, logic, or component state. we will explore how to conditionally add attributes for elements using VueJS.
These are the following ways to conditionally add an attribute for an element in VueJS:
Steps to Create the Vue.js Application
Step 1: Install Vue CLI
- If you haven’t already installed Vue CLI, install it globally using npm
npm install -g @vue/cli
Step 2: Create a New Vue.js Project
- Run the following command to create a new Vue.js project
vue create conditional-attribute-gfg-nikunj
- Follow the prompts to set up the project. You can choose the default preset for simplicity.
Step 3: Navigate to the Project Folder
cd conditional-attribute-gfg-nikunj
Step 4: Serve the Application
- Start the development server
npm run serve
Project Structure:
Project StructureUpdated Dependencies:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0"
},Using Vue's v-bind Directive
Vue's v-bind directive is used to dynamically bind an attribute to an element. We can use this directive to bind an attribute conditionally by controlling the expression inside the v-bind.
Syntax:
<element v-bind:attribute="condition ? value : null"></element>
Example: This example shows the use of v-bind Directive to conditionally add an attribute for an element in VueJS.
JavaScript
<template>
<div>
<!-- Conditionally add 'disabled' attribute to the button -->
<button v-bind:disabled="isDisabled">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
isDisabled: true, // Change to false to see the difference
};
},
};
</script>
Output:
OutputUsing Dynamic Object Syntax in v-bind
Vue's v-bind can accept an object, allowing you to add or remove multiple attributes dynamically. You can conditionally control which attributes get added by specifying key-value pairs within the object.
Syntax:
<element v-bind="{ attribute: condition ? value : null }"></element>Example: This example shows the use of Dynamic Object Syntax in v-bind to conditionally add an attribute for an element in VueJS.
JavaScript
<template>
<div>
<!-- Conditionally add multiple attributes -->
<input v-bind="{ readonly: isReadOnly, disabled: isDisabled }" value="GFG"/>
</div>
</template>
<script>
export default {
data() {
return {
isReadOnly: true,
isDisabled: false,
};
},
};
</script>
Output:
Output
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics