Search code examples
javascriptarraysvue.jsvuejs2vuex

How to use Data through components


I do have two components, the first one is the component that i use to show a list of items, the second component is about the styling and how the items should be displayed.

The items are stored in an array that is inside the app.vue file

the question i have is, how can i use the array through the two components. how can i use it in the second component to fetch the elements of the item and place them like the title and so. And how can i loop through all of the items in order to show them in the component where i display them all.


Solution

  • This can be achieved by using a for loop and component props

    For example

    In two files:

    1. Parent component, for example FruitComponent.vue
    <template>
        <fruit-list v-for:"fruitTitle in fruitsList" :title="fruitTitle"></fruit-list>
    </template>
    <script>
        export default{            
            data () {
                return {
                    fruitsList: ["fruit1", "fruit2", "fruit3"]
            } 
        }
    </script>
    
    1. Child component, for example FruitItem.vue
    <template>
        <h3>{{fruitsItem}}</h3>
    </template>
    <script>
        export default{            
            props: {fruitTitle : String}
        }
    </script>
    

    Alternatively, if you have a one-time usecase

    (This is only recommended for super small components as the whole HTML for you child component goes into the "template" attribute when creating the component. Creating a new file will make it cleaner)

    1. Parent component containing
    <div id="fruits-component">
      <ol>
        <fruits-list v-for="fruit in fruitsItems" :fruits-item="fruit"></fruits-list>
      </ol>
    </div>
    
    1. Create a child component you are trying to render dynamically
    Vue.component('fruits-list', {
      props: ['fruitsItem'],
      template: '<h3>{{fruitsItem.name}}</h3>'
    });
    
    1. Registering the component as a child to fruits-component
    new Vue({
      el: '#fruits-component',
      data: {
        fruitsItems: [
          {name: 'first fruit'},
          {name: 'second fruit'}
        ]
      }
    });