How to display input with the click of a button in vue.js?

Member

by domenico , in category: Javascript , 4 months ago

How to display input with the click of a button in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 4 months ago

@domenico 

You can display input with the click of a button in Vue.js by using a combination of data properties, v-model directive, and a method to toggle the visibility of the input. Here's an example code snippet to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
  <div>
    <button @click="toggleInput">Show Input</button>
    <input v-if="showInput" v-model="inputValue" type="text" placeholder="Enter text here">
  </div>
</template>

<script>
export default {
  data() {
    return {
      showInput: false,
      inputValue: ''
    };
  },
  methods: {
    toggleInput() {
      this.showInput = !this.showInput;
    }
  }
};
</script>


In this code snippet:

  1. We have a button with a click event listener that calls the toggleInput method when clicked.
  2. The showInput data property is used to toggle the visibility of the input field. Initially set to false, it will show the input field when set to true.
  3. The inputValue data property is used to bind the value of the input field using the v-model directive.
  4. The toggleInput method changes the value of showInput from true to false or vice versa each time it is called, thereby displaying or hiding the input field accordingly.