Home » vue » Set Component prop for all instances / Pass same data to all Component instances

Set Component prop for all instances / Pass same data to all Component instances

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a Component where each instance needs some data being passed onto it, that Component is used multiple times and all instances of the component should receive the same data/prop.

<my-component :someProp="someValue"></my-component>
<my-component :someProp="someValue"></my-component>
<my-component :someProp="someValue"></my-component>
<!-- ...and lots more... -->

This is my current method:

Which gets kind of redundant, how can I pre-populate this someProp for ALL instances of my component?
I tried Vue.extend() but cannot figure out what syntax it expects, the documentation is not clear enough on that part.
This is how I imagined it to work:

// App.vue
import MyComponent from './components/MyComponent'

const PreConfiguredComponent = Vue.extend(MyComponent, {
  props: {
    someProp: "someValue"
  }
})

export default {
  name: 'app',
  data: () => ({}),
  components: {
    MyComponent: PreConfiguredComponent
  }
}

You get the idea, I don’t know how to express it better. Doesn’t have to be done with props but I don’t know other methods to pass data along.

Answers:

There are quite a lot of different ways to approach this. I doubt this will be anything like an exhaustive list but I can give some sense of the possibilities.

1. Store the value globally

The obvious choice here is the Vuex store. Just put the relevant data in the store and then the components can grab what they need.

However, a global store doesn’t have to be Vuex. If you have no other reason to introduce Vuex then you might prefer something more ad hoc.

An alternative to the store is to hold the data on $root, an approach described in the official documentation:

https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch

A further alternative is just to have a .js file that can hold the data as a singleton. There are various ways to do it but in its simplest form it might be something like this:

export default {
  myData: null
}

You’d then import that object and read/write the value of myData as required. It won’t necessarily be reactive but I’m assuming that the initial value would be set at the start, before the application is created, and wouldn’t change after that.

2. Store the value on the Vue prototype

This is quite similar to the above but I think it warrants a separate mention. It’d look something like this:

Vue.prototype.$myComponentData = 'someValue'

Then within any component you could access the value via the property $myComponentData.

Documentation: https://vuejs.org/v2/cookbook/adding-instance-properties.html

3. Provide/Inject

The provide/inject mechanism is one of the lesser known Vue features but it provides an alternative to using props to pass data down to child components. It has various pros and cons and typically you’d try to use props instead.

https://vuejs.org/v2/api/#provide-inject

In short, it allows a component to provide a named value to all of its descendants without needing to explicitly pass it to each one individually. The descendant components can then choose which named properties they would like to have injected.

You wouldn’t be able to use provide/inject to pass different values to descendant components but in your case the value is the same so it should work.

If you think this approach might be for you then I suggest some further reading:

https://blog.logrocket.com/how-to-make-provide-inject-reactive/

4. Refactor to remove the duplication

While this is unlikely to be the solution you go with I do think it is worth mentioning.

The starting premise for the question seems to be that passing the prop explicitly is a form of duplication. Extra noise and extra effort with the potential to make mistakes.

Potentially we can remove that duplication while still passing the prop. The key here is to refactor the template so that the child component only features once.

Obviously that would need to be within a loop so that we still get all the desired components. That loop would need a suitable data structure to drive it so that all the right components get created.

I assume the template in the question is a simplification. If you really do have several instances consecutively then refactoring to use a v-for should be pretty trivial. If, as seems more likely, the components are nested in various places within the layout then it can get unwieldy trying to encode that in data structures just to avoid a bit of template duplication.

Hopefully the idea is clear but if not you could give this a read:

https://michaelnthiessen.com/reducing-redundant-repetition

5. Dynamic components

This is what’s alluded to in the question. There are various ways to do it but the core of the idea is that we change our component definitions at runtime. That doesn’t necessarily mean creating a new component, it could equally mean prodding something into an existing component definition. We’ve already seen a variation of this idea with the Vue.prototype approach mentioned earlier.

In theory it could be done with the default value of a prop but it seems unnecessary to use a prop unless that prop is going to be set from the outside in the usual way in some cases.

We could set it as a property using data but personally I would be tempted to use a variation of the Vue.prototype trick to add the property to the component’s own prototype:

MyComponent = Vue.extend({
  template: `<div>{{ value }}</div>`
})

MyComponent.prototype.value = 'some value'

new Vue({
  el: '#app',

  components: {
    MyComponent
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>

Using the prototype is relatively cheap from a performance perspective. There are potential problems with reactivity but they would only apply if the value can change, which it can’t in this case.

Just to illustrate the prop and data approaches explicitly:

MyComponent = {
  template: `<div>{{ value }}</div>`
}

PreConfiguredComponent = Vue.extend({
  extends: MyComponent,

  props: {
    value: {
      default: 'some prop value'
    }
  }
})

new Vue({
  el: '#app',

  components: {
    MyComponent: PreConfiguredComponent
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>

and:

MyComponent = {
  template: `<div>{{ value }}</div>`
}

PreConfiguredComponent = Vue.extend({
  extends: MyComponent,

  data () {
    return {
      value: 'some data value'
    }
  }
})

new Vue({
  el: '#app',

  components: {
    MyComponent: PreConfiguredComponent
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>

You could equally try to tweak the imported MyComponent directly rather than extending it.