How can I control the content of <input> element with Vue?

Viewed 50

I want to have full control over the content of <input> element.

With React, I can do that like:

import { useState } from "react";

function Form() {
  const [value, setValue] = useState("");

  const onSubmit = (event) => {
    event.preventDefault();
    // Do something with `value`
  };

  const onChange = (event) => {
    const { value } = event.target;
    // For example, users can type only uppercase letters
    if (value === value.toUpperCase()) {
      setValue(value);
    }
  };

  return (
    <form onSubmit={onSubmit}>
      <input onChange={onChange} value={value} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default Form;

In Vue, however, I cannot control <input> like:

<script setup>
import { ref } from "vue";

const value = ref("");

const onSubmit = () => {
  // Do something with `value`
};

const onInput = (event) => {
  // For example, users can type only uppercase letters
  if (event.target.value === event.target.value.toUpperCase()) {
    value.value = event.target.value;
  }
};
</script>

<template>
  <form v-on:submit.prevent="onSubmit">
    <input v-on:input="onInput" v-bind:value="value" />
    <button type="submit">Submit</button>
  </form>
</template>

It looks Vue doesn't control the <input> element's value attribute and Vue's value ref differs from value in DOM.

How can I do the same thing as React in Vue? Thank you in advance.

1 Answers

If you want the input element content to be only updated on a specific condition.

One solution is on input event, you need to reset the input element value with the ref value, if the condition doesn't match.

Ex:

<script setup>
import { ref } from 'vue'

const inputValue = ref('')
const onSubmit = () => {
  console.log(inputValue.value)
  // Do something with `value`
}

const onInput = (event) => {
  // For example, users can type only uppercase letters
  const value = event.target.value
  if (value === value.toUpperCase()) {
    inputValue.value = value
  } else {
    event.target.value = inputValue.value
  }
}
</script>

<template>
  <form v-on:submit.prevent="onSubmit">
    <input @input="onInput" :value="inputValue" />
    <button type="submit">Submit</button>
  </form>
</template>

This is a live code example of what you are looking for.

https://stackblitz.com/edit/vue3-script-setup-with-vite-ze8fvb?file=src/App.vue

Related