Daniel Santos
Daniel Santos

Reputation: 15778

How expose child element v-model as the vue component v-model

I Was using a simple text area in my vue component.:

<input v-model="someRootProperty"/>

I would like to encapsulate this input inside another component, for instance

<template>
    <div>
        <div>...</div>
        <input v-model="???"/>
    </div>
</template>

I would like to use

<my-component v-model="someRootProperty" />

instead and them bypass this to the input inside the component.

What should I do inside the component to expose its input v-model as the component v-model?

Upvotes: 1

Views: 885

Answers (1)

Andreas
Andreas

Reputation: 1099

<input v-model="someRootProperty"/>

Is the same as (syntactic sugar):

<input :value="someRootProperty" @input="someRootProperty = $event.target.value"/>

That means that you could accept value as a prop in the component and emit input to achieve the same thing.

MyComponent.vue

<template>
  <input :value="value" @input="$emit('input', $event.target.value)>
</template>

<script>
export default {
  props: ['value']
}

And then use it like this.

<MyComponent v-model="someRootProperty"/>

Upvotes: 8

Related Questions