A
A
Andrew2022-04-21 15:58:03
Vue.js
Andrew, 2022-04-21 15:58:03

Where in the code is it correct to do validation/formatting?

There is a custom input component

<template>
      <input
        type="text"
        placeholder="Не введено"
        :value="modelValue"
        :disabled="disabled"
        @input="updateModelValue"
      />
</template>

<script>
import { ref } from '@vue/reactivity';
import { computed } from '@vue/runtime-core';

export default {
  name: 'CustomInput',
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    modelValue: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const updateModelValue = (event) => {
      emit('update:modelValue', event.target.value);
    };

    return {
      updateModelValue,
    };
  },
};
</script>


Accordingly, another component has v-model. Where is it correct to insert string formatting here (for example: trimming spaces, limiting the length, input mask, etc.)? I tried to insert it into the updateModelValue method, the value changes, but only when the focus disappears from the input, and not when entering each character. The simplest formatting on which I tested:
export default class Filter {
  #value = '';

  constructor(v) {
    this.#value = v;
  }

  trim() {
    this.#value = this.#value.trim();
    return this;
  }

  max(len) {
    this.#value = this.#value.splice(0, len);
  }

  get() {
    return this.#value;
  }
}
...
  setup(props, { emit }) {
    const updateModelValue = (event) => {
      const filtered = (new filter(event.target.value)).trim().max(5).get();
      emit('update:modelValue',  filtered);
    };

    return {
      updateModelValue,
    };
  },

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question