skip to Main Content

I’ve got a myInput.vue component which accepts a v-model prop and captures the value of v-model as modelValue, like so:

<template>
  <input type="text" :value="modelValue" />
</template>

<script setup>
  const props = defineProps({
    modelValue: {
      type: [String, null],
      required: true
    }
  })
</script>

If I’m using v-bind as opposed to v-model, how would I go about capturing the value from within the component? Using bindValue doesn’t work.

2

Answers


  1. What about using the defineModel macro :

    <template>
      <input type="text" v-model="modelValue" />
    </template>
    
    <script setup>
    const modelValue = defineModel()
    </script>
    
    Login or Signup to reply.
  2. As far as I understand, you need to emit an event in the child component and catch it in the parent component.

    You can do it like this:

    <template>
      <input type="text" :value="modelValue" @input="updateValue" />
    </template>
    
    <script setup>
      const props = defineProps({
        modelValue: {
          type: [String, null],
          required: true
        }
      });
    
      const emit = defineEmits(['update:modelValue']);
    
      function updateValue(event) {
        emit('update:modelValue', event.target.value);
      }
    </script>
    

    There are two ways to use this component:

    <my-input :modelValue="text” @update:modelValue="(newValue) => text.value = newValue" />
    

    or

    <my-input v-model="text" />
    

    I’m assuming that text is a ref variable.

    It’s worth remembering that v-model is basically just an add-on to v-bind and v-on, here’s a more detailed description: https://vuejs.org/guide/components/v-model.html#basic-usage.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search