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.
This can be achieved by using a for loop and component props
For example
<template>
<fruit-list v-for:"fruitTitle in fruitsList" :title="fruitTitle"></fruit-list>
</template>
<script>
export default{
data () {
return {
fruitsList: ["fruit1", "fruit2", "fruit3"]
}
}
</script>
<template>
<h3>{{fruitsItem}}</h3>
</template>
<script>
export default{
props: {fruitTitle : String}
}
</script>
(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)
<div id="fruits-component">
<ol>
<fruits-list v-for="fruit in fruitsItems" :fruits-item="fruit"></fruits-list>
</ol>
</div>
Vue.component('fruits-list', {
props: ['fruitsItem'],
template: '<h3>{{fruitsItem.name}}</h3>'
});
new Vue({
el: '#fruits-component',
data: {
fruitsItems: [
{name: 'first fruit'},
{name: 'second fruit'}
]
}
});