[Vuejs]-How keep the text box show if it is empty in VueJs

0👍

Several ways to do that:

  1. Only update the boolean that filter empty text boxes after they’re edited. (i.e. onblur event). You could have a boolean that list the text boxes to hide, but only update it after an onblur event occurs. So it won’t be updated while you write in a text box.

  2. Consider a text box empty only if it’s empty && it doesn’t have current focus (i.e. use the @focus event or get the textbox html element with a $ref to get the html element and use document.activeElement === myTextBox)

This is not a final solution because we don’t have enough clues about what does you code look like. But I guess it’s a start to resolution 🙂

0👍

As @jaynyxed mentioned, you could use focusin and focusout to help you achieve your goal, I write an example here in code pen and I’ll let the code here, so if you cannot open the link I hope you understand how it works.

<template>
  <div id="app">
   <input 
          v-if="showA" 
          type="text" 
          v-model="inputA" 
          @focusin="visibleA = true" 
          @focusout="visibleA = false">
    
    <input 
           v-if="showB" 
           type="text" 
            v-model="inputB"
           @focusin="visibleB = true"
           @focusout="visibleB = false">
    
    <input type="checkbox" id="checkbox" v-model="hide">
    <h5>{{ inputA }} </h5>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hide: false,
      inputA: '',
      inputB: '',
      visibleA: false,
      visibleB: false,
    };
  },
  
  computed: {
    showA() {
      return (this.inputA.length > 0 || !this.hide) || this.visibleA;
    },
    
    showB() {
      return (this.inputB.length > 0 || !this.hide) || this.visibleB;
    }
  }
}
</script>

Off course you could do that in many other ways, and maybe this one is not the best possible, but it shows my point.

PS: If you have dozens of input box, I recommends you to create a component to handle that logic, and then you just receive an hide props in your component and emits input for example.

Leave a comment