I have a fetch request in Home.vue file and I want to use the same data to another vue file (AllJobs.vue) with the same component(props). How I can achieve this without make a new fetch request in AllJobs.vue? I heard that I can use Pinia, but for a small project like this I wonder if it is a simpler solution?
Home.vue
<div >
<div v-for="job in jobs.reverse().slice(0, 5)" :key="job.id" >
<JobComponent :position="job.position" :department="job.department" :location="job.location"/>
</div>
</div>
</template>
<script>
import JobComponent from '../components/JobComponent.vue'
export default {
name: 'Home',
components: { JobComponent },
data() {
return {
jobs: [],
}
},
mounted() {
fetch("http://localhost:3000/jobs")
.then(res => res.json())
.then(data => this.jobs = data)
.catch(err => console.error(err.message))
}
}
</script>
AllJobs.vue
<div >
<JobComponent />
</div>
</template>
<script>
import JobComponent from '../../components/JobComponent.vue'
export default {
name: "AllJobs",
components: { JobComponent },
}
</script>
JobComponent.vue
<div >
<div >{{ position }}</div>
<div >{{ department }}</div>
<div >
<span >
location_on
</span>
{{ location }}
</div>
<span >
arrow_right_alt
</span>
</div>
</template>
<script>
export default {
props: ['position', 'department', 'location'],
}
</script>
CodePudding user response:
We don't know the structure of your files here, but you can use the following:
- props to pass the state from parent to children