3

I'm trying to use vuejs to display a list of instances of a child component. The child component has input fields that a user will fill in.

The parent will retrieve the array of data to fill in the child components (If any exists), but since they're input fields the child component will be making changes to the value (Which generates errors in the console, as child components aren't supposed to change values passed from the parent).

I could just be lazy and just do everything at the parent level (i.e. use a v-for over the retrieved array and construct the list of elements and inputs directly in the parent and not use a child component at all), but I understand that it's not really the vuejs way.

I'm not very familiar with child components, but I think if it was just static data I could just declare props in the child component, and fill it from the parent. However what I kind to need to do is fill the child component from the parent, but also allow changes from within the child component.

Could someone please describe the correct way to achieve this?

Thanks

1 Answer 1

3

You can use inputs on child components. The pattern is like this (edit it's the same pattern for an array of strings or an array of objects that each have a string property as shown here):

data: function() {
  return {
    objects: [ { someString: '' }, { someString: '' } ]
  }
}

<the-child-component v-for="(object, i) in objects" :key="i"
  v-model="object.someString"
></the-child-component>

Then, in the child component:

<template>
  <div>
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    />
  </div>
</template>

export default {
  name: 'the-child-component',
  props: ['value'],
}

See it described here: https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components

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

6 Comments

If you're binding :value and @input on <the-child-component>, you might as well use v-model, ie <the-child-component v-model="someString"/>
Thanks, @Phil. Edited.
Doesn't your child component need a value prop now?
@danh I don't think this will work for my use case. In the parent I want to render an array of child components, so I don't think I can use v-model in the way you describe. Could you please provide an example where an array of child components is used? For the sake of simplicity you can assume that it's just an array of components with a single string property if that easier to demonstrate.
@Steviebob - same idea for an array of child components. See edit.
|

Your Answer

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