1

I have an array of generic child components in my parent component:

<component v-for="item in items" :key="item.id" :is="componentName">

I can get a child via this.$refs, but I can't set a new value for a prop :is like:

this.$refs[id][0].is = 'MyNewComponentName'

How can I set a value of component instance property in a code?

2
  • That's not how props work. If you want to change the value bound to the is prop, then change the value of componentName, eg this.componentName = 'MyNewComponentName. See vuejs.org/v2/guide/components-dynamic-async.html Commented Oct 21, 2019 at 11:23
  • @Phil, But if I will change componentName, so it will be applied to all array items, but I need to apply it only to one instance in this array. Commented Oct 21, 2019 at 11:32

1 Answer 1

3

First define your prop structure like

{
  ...item, // to use your current variables
  componentName: 'MyExistingComponentName'
}

Receive the prop and bind it to a data variable, so something like

data: function() {
  returns {
     items: this.propItem
  }
}

Make the required adjustment in your tag

<component v-for="item in items" :key="item.id" :is="item.componentName">

Now you got 2 options, you can either change the item.componentName by referencing this.items in a method, finding the index and changing it or you could get the parent to change the value of the prop using a custom event using $.event(event-name, 'MyNewComponent`). Both methods are fine, it really depends on your requirements.

Refer to https://v2.vuejs.org/v2/guide/components-custom-events.html You could also read stackoverflow questions on mutating prop values.

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

3 Comments

All components have default name property to define their names to be used as childs. So looks like I don't need to create a new one (componentName).
Thing is, unless you have a variable bound, you can't dynamically change data. If the componentName property is not in the props or data, there is no way to change it. This way you can handle more complicated scenarios where you have multiple different component names and default values. Btw you havn't mentioned the error your current solution throws.
I can't understand how :is="item.componentName" is connected with components I want to render conditionally in your solution. item is just an element in array. It isn't instance of a component.

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.