DEV Community

Cover image for How to emit a value from an input component Vue 3.
Denisse Abreu
Denisse Abreu

Posted on • Edited on

How to emit a value from an input component Vue 3.

Hello 👋🏼, I will teach you how to emit a value from an input component using Vue 3 Composition API. Our working environment is Vue 3 with Vite and TypeScript.

Install your Vue 3.

Run in your terminal npm init vue@latest.
Vue will scaffold the project and ask you some questions.

Project name: vue-input-tutorial
Add TypeScript? Yes
Enter fullscreen mode Exit fullscreen mode
  • After installing Vue 3, go to the newly created project and install its libraries.
cd vue-input-tutorial
npm install
Enter fullscreen mode Exit fullscreen mode

Create the Component.

  • Go to the Components folder and create a form input component FormInput.vue.

  • inside the form input component, copy the following code.

<script setup lang="ts">
import { defineProps, defineEmits } from "vue";

defineProps<{
  modelValue: string;
  name: string;
  type: string;
}>();

defineEmits(["update:modelValue"]);
</script>

<template>
  <div>
    <label class="px-3" for="name">{{ name }}</label>
    <input
      :type="type"
      :value="modelValue"
      @input="
        $emit('update:modelValue', ($event.target as HTMLInputElement).value)
      "
      :placeholder="name"
    />
    <br />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Use Your Component.

  • Go to App.vue and import the form input component.
<script setup lang="ts">
import { ref } from "vue";
import FormInput from "./components/FormInput.vue";

const email = ref("");

// output value key by key
const onInput = (e: { target: { value: string } }) => {
  email.value = e.target.value;
};

// output value on submit
const Submit = () => {
  console.log(email.value);
};
</script>

<template>
  <form @submit.prevent="Submit">
    <FormInput
      v-model="email"
      name="E-mail"
      type="email"
      @input="onInput"
    />
      <button type="submit">Submit</button>
    </form>
    <div>{{ email }}</div>
</template>
Enter fullscreen mode Exit fullscreen mode
  • In the code above, I added two different examples, one that will output every change in the input, and the other will submit a form and console log the input value. Thanks for reading 👋, Visit my website at codingpr.com

Top comments (1)

Collapse
 
thammer67 profile image
thammer67

I'm not sure if this is a feature of Vue 3.2 but I found that if the input is the only element in the component, you don't even need to define an emit or attach it in the click handler as long as modelValue is the prop that is defined.