Home > Software design >  Vue 3 pattern for input
Vue 3 pattern for input

Time:09-18

I want to create input in which I can replace entered chars with empty chars if the pattern doesn't match.

template:

<input
  type="text"
  :value="val"
  @input="input"
/>

script:

import { ref } from "vue";
export default {
  setup() {
    let val = ref("");
    const input = ({ target }) => {
      val.value = target.value.replace(/[^\d]/g, "");
    };
    return { val, input };
  },
};

Sandbox: https://codesandbox.io/s/vue-3-input-forked-rqjres?file=/src/components/Form1.vue:138-352

CodePudding user response:

You can use watcher to remove entered numbers:

const { ref, watch } = Vue
const app = Vue.createApp({
  setup() {
    let val = ref("");
    watch(val,
      (newValue, oldValue) => {
        val.value = newValue.replace(/\d /g, "")
      },
    );
    return { val };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div>
    <input
      type="text"
      placeholder="Full Name"
      autocomplete="off"
      v-model="val"
    />
  </div>
  {{ val }}
</div>

CodePudding user response:

If you want to allow the user to input only numbers, you can also do this natively in HTML with <input type="number">.

CodePudding user response:

You can achieve this by updating the value of input directly from the @input event.

Live Demo :

const app = Vue.createApp({
  data () {
    return {
      val: null
    }
  },
  methods: {
    checkPattern(event) {
      return event.target.value.replace(/[^\d]/g, '')
    }
  }
})

app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<div id="app">
   <input type="text" :value="val" 
  @input="val=checkPattern($event)">
</div>

  • Related