Ralph
Ralph

Reputation: 37

Vue: Hand Over An Object To A Component For It To Use

In my app I have a list component which I use inside another component. Currently, it looks something like this:

<script setup>
const seed = [
  {
    key: value,
    anotherKey: anotherValue,
  },
  // and so on...
];
</script>

<template>
  <ul>
    <li v-for="element in seed" :key="element.key" :anotherKey="element.anotherKey">
  </ul>
</template>

My question is: Is it possible to somehow "hand over" an object inside the parent component which uses this list component instead of getting the object from within the list component's script tag?

Upvotes: 0

Views: 128

Answers (1)

Hackerbyday
Hackerbyday

Reputation: 101

You can use provide in your parent component to pass an object to your child components.

ParentComponent.vue (Untested code)

<script setup>
const seed = [
  {
    key: value,
    anotherKey: anotherValue,
  },
  // and so on...
];

provide('seed', seed)
</script>

ChildComponent.vue

<script setup>
const seed = inject('seed')
</script>


<template>
  <ul>
    <li v-for="element in seed" :key="element.key" :anotherKey="element.anotherKey">
  </ul>
</template>

You can read about provide in compositions. https://vuejs.org/api/composition-api-dependency-injection.html

Upvotes: 2

Related Questions