How to use v-if and v-else In Vue
In this approach, we are using the v-if and v-else directives to conditionally render input fields based on the value of the condition variable. When a user clicks on the button the input field is been switched and a disabled input field is been shown.
Syntax:
<input v-if="!condition" v-model="textInput">
<input v-else :readonly="true" :style="{ 'background-color': '#eee' }" v-model="textInput">
Example: The below code example illustrates the use of a v-if and v-else to conditionally disable the input taking in VueJS.
HTML
<!DOCTYPE html> < head > < title >Example 2</ title > < script src = "https://cdn.jsdelivr.net/npm/vue@2" ></ script > </ head > < body > < div id = "app" > < h1 > Using v-if and v-else</ h1 > < button @ click = "disableCondition" > Toggle Input </ button > < input v-if = "!condition" v-model = "textInput" > < input v-else :readonly = "true" :style = "{ 'background-color': '#eee' }" v-model = "textInput" > </ div > < script > new Vue({ el: '#app', data: { textInput: '', condition: true }, methods: { disableCondition: function () { this.condition = !this.condition; if (this.condition) { this.textInput = ''; } } } }); </ script > </ body > </ html > |
Output:
How to Conditionally Disable the Input in VueJS ?
In VueJS, we can conditionally disable the input-taking field. In this article, we will learn to conditionally disable the input-taking field by using two different approaches listed below:
Table of Content
- Using :disabled Property
- Using v-if and v-else