[Vuejs]-How to make a text box which shows inverts a input

0👍

Html:

 <input v-model="someStr" @input="reverseString"/>
{{ reverseStr }}

Script:

data() {
 return {
  someStr: '',
  reverseStr: ''
 }
}



 methods: {
  reverseString() {
   this.reverseStr = this.someStr.split("").reverse().join("")
  }
}

0👍

as far as i understood you want to invert the input in real time with @keyup ,, and also keeping the sentence in the input field , after some digging , you cannot use a v-model to change the input while still typing but i found a good work around ,

input inverted and looks like in the same input field , using absolute positioning and two input one for input (hidden but on top) an other for output (visible but the bottom one)
here is the live preview :Sandbox preview

<template>
  <div class="hello">
    
    <div class="invert">
      <input type="text" v-text="input" class="input"   @keyup="handle" >
      <input type="text" v-model="output" class="output"  >
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      input : '',
    }
  },
  computed : {
    output (){
        return this.input.split("").reverse().join("");
    }
  },
  methods : {
    handle(event) {
         this.input = event.target.value;
    }
  }
}
</script>
<style scoped>
  .invert {
    position : relative ;
    width: 200px;
    height: 20px;
    margin: 0 auto;
  }
  .output , .input{
    position: absolute;
    width: 100%;
    right: 0;
  }
  .input {
    z-index: 5;
    opacity : 0 ;
  }
    .output {
    z-index: 0;
    opacity : 1 ;
  }
</style>

best solution

one input !

you may experience some flickering when the input appears non inveted first , its not there anymore i dont know how it went away , but it happens because v-model bind before the handle function if you faced some please check the third option . check it here :

sanbox preview

<template>
  <div class="hello">
    <div class="invert">
      <input type="text" v-model="input" class="input" @input="handle" />
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      input: "",
    };
  },

  methods: {
    handle(event) {
      if (this.input.length > 1) {
        this.input =
          this.input[this.input.length - 1] +
          this.input.substring(0, this.input.length - 1);
      }
    },
  },
};
</script>

second option two inputs

if the input appears non inverted first then you only left with the first option (two inputs coz we cant be faster than v-model binding) but this time i used transparent instead of opacity 0 wich will let you select the input ! update the first style with :
sandbox preview


.input {
  z-index: 5;
  background: transparent;
}


Leave a comment