2

I'm trying to build a custom HTML <input> component for VueJS3. I've been following this tutorial:

https://dev.to/viniciuskneves/vue-custom-input-bk8

So far I managed to get the CustomInput.vue component to work and emit the modified value back to the parent App.Vue.

<template>
<label>
{{ label }}
<input type="text" :name="name" :value="value" @input="onInput" @change="onChange" />
  </label>
</template>

<script>
export default {
  name: 'CustomInput',
      props: {
    label: {
      type: String,
      required: true,
    },
    value: {
      type: String,
      required: true,
    },
  },
  computed: {
    name() {
      return this.label.toLowerCase();
    },
  },
  methods: {
    onInput(event) {
      this.$emit('input', event.target.value);
    },
    onChange(event) {
      this.$emit('change', event.target.value);
    },
  },
}
</script>

What I don't understand is - how will the emitted events be detected by the parent App.vue component? I can't see it happens, and I can't find it in the tutorial.

My App.Vue looks like this:

<template>
<custom-input :label="'Name'" :value="name"></custom-input>
<div>{{ name }}</div>
</template>

<script>
import customInput from "./components/CustomInput.vue";

export default {
  components: { customInput },
  name: "App",
  data: function () {
return {
  name: "",
};
  },
  mounted() {
    this.name = "Thomas";
  },
};
</script>

Thanks in advance for any help :-)

2 Answers 2

7

This tutorial is for Vue 2 - for Vue 3 there is another tutorial (https://www.webmound.com/use-v-model-custom-components-vue-3/)

Emitting input event works in Vue 2 only - for Vue 3 you will have to emit update:modelValue and also use modelValue as a prop instead of just value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ivo Gelov for the link to the Vue3JS Tutorial - I managed to get it working.
0

You can do it right in your template.

<custom-input :label="'Name'" :value="name" @change='name=$event' @input='name=$event'></custom-input>

You can also use a method or computed with setter as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.