[Vuejs]-VUE3 pass data between files

1👍

When it comes to handling API requests and sharing data between components, what you need is some state management solution like pinia.

You can fetch and save your data in a store and then use it in any component:

jobs.js

export const useJobsStore = defineStore('jobs', {
  state: () => ({ jobs: [] }),
  actions: {
    fetchJobs() {
      fetch("http://localhost:3000/jobs")
        .then(res => res.json())
        .then(data => this.jobs = data)
        .catch(err => console.log(err.message))
    },
  },
})

App.vue

import { mapActions } from 'pinia
import { useJobsStore } from './jobs.js'

export default {
  methods: {
    ...mapActions(useJobsStore, ['fetchJobs'])
  },

  mounted() {
    this.fetchJobs()
  }
}

Home.vue and AllJobs.vue

import { mapState } from 'pinia'
import { useJobsStore } from './jobs.js'

export default {
  computed: {
    // this makes this.jobs available in script and template
    ...mapState(useJobsStore, ['jobs'])
  }
}

One thing which is debatable is where to call fetchJobs action

  1. In App.vue or main.js – this will fetch data as soon as you open the app, but can be unnecessary if the page you visit doesn’t even use the data.
  2. In each page that uses the data – solves the previous problem, but fetches the same data multiple times.
  3. In each page that uses the data (with caching) – you can modify fetchJobs to make a request only if the data haven’t been fetched already. This way the app will fetch the data as soon as you visit some page which uses it. And if you visit another page, it will use the cached value instead of making a request

There isn’t a singe best approach, which one to pick depends on your needs

Leave a comment