[Vuejs]-Sharing data between all Vue.js components

0👍

If I understand your main issue, you could use something like an instance property or a javascript file to hold variables in client-side storage.


From what I understand, what you need is a way to first get data from your MySQL using one component, and then second, use that data in all the rest of your components. If so, I had this need with my current project about 2 months ago.

The only problem is that I’m not using Laravel/Vue but Vue.js, VueApollo, and GraphQL. Although, I’m pretty sure —and hope— the way that I fixed my issue will only differ in syntax from the way you could solve yours.


I used a component to query some info from the user right after they log in.

Vue/Apollo Query

apollo: {
  // Simple query that gets user info
  me: {
    query: gql`  //GraphQL
      {
        me {
          id
          fullName
        }
      }
    `,
    loadingKey: "isLoading" //tracks results that are still loading.
  }
}

Then I wanted to store the user’s ‘fullName’ somewhere so that my navigation component could always use it. So I created a file:

src/config/credentialStore.js

In this file I created a displayName variable like this:

export const credentialStore = {
  displayName: "",
  userID: ""
};

Back in the component where I have the ‘me’ query, I destructured the data that was returned from the query with a function.

apollo: {
  // Simple query that gets user info
  me: {
    query: gql`
      {
        me {
          id
          fullName
        }
      }
    `,
    loadingKey: "isLoading",
    result({ data }) {   //data is basically an object with the results of the query

      this.$credentials.userId = data.me.id;
      this.$credentials.displayName = data.me.fullName;  
    } //using this.$credentials.displayName will let me use that string from any component.
  }
}

So you would do something like that and then maybe something like this:

<script>
export default {
    data(){
        return{
            editmode: false,
            fabriquants :{},
            form: new Form({
                id: this.$credentialStore.id,
                fabnom:this.$credentialStore.fabnom, //what's a fabnom? 🤔

                •   •   • 
            })
        }
    }, 

I hope this helps you or someone else.

Leave a comment