Sasha Astanin
Sasha Astanin

Reputation: 50

How to change value of component property in a code in Vue.js?

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?

Upvotes: 1

Views: 4895

Answers (1)

Varun Agarwal
Varun Agarwal

Reputation: 1587

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.

Upvotes: 3

Related Questions