[Vuejs]-How to hide part of input value in v-text-field?

1👍

There could be more methods to do this but that relies on your UX as well like how you want to show the hidden characters and when to show the full name, etc.

I can think about the subsequent technique-

  1. On the user profile page’s mounted hook, replace the desired characters with the special symbol (*), and make your text field read-only, so it won’t update.
  2. When focusing on the text field, show the full name inside it and make it editable.
  3. When focusing out from the text field, save the updated name to your DB, replace the desired characters with the special symbol (*), and make the text field read-only again.

Here is the functioning demo-

<!DOCTYPE html>
<html>
  <head>
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
  </head>
  <body>
    <div id="app">
      <v-app>
        <v-text-field
          label="username"
          :readonly="readonly"
          v-model="updatedName"
          @focus="onFocus"
          @blur="onBlur"
          ></v-text-field>
      </v-app>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
    <script>
      new Vue({
        el: '#app',
        vuetify: new Vuetify(),
        
        data() {
          return {
            readonly: true, // initial state
            username: "nehasoni", // this should come from API
            updatedName: null, // for v-model use
          }
        },
        
        mounted() {
          this.hideName()
        },
        
        methods: {
          hideName() {
            // replace all characters except first with a *
            this.updatedName = this.username.replace(/.(?=.{1,}$)/g, '*');
          },
          
          onFocus() {
            // make text field editable 
            this.readonly = false;
            // show full name
            this.updatedName = this.username;
          },
          
          onBlur() {
            /** 
            * save your name to database and assign response to the username, like this-
            * this.username = api_response
            * For now, I am using updatedName as API response
            */
            this.username = this.updatedName;
            // make text field read only again
            this.readonly = true;
            // Hide the name again.
            this.hideName();
          }
        }
      })
    </script>
  </body>
</html>

Leave a comment