8

My main.js file references #app as the el, and then on ready it sends an HTTP request to my API to get data on the user based on their token taken from localStorage.

It sets the data like so when the response is returned:

this.$http.get('/me', function(data) {
  this.$set('me', data.me);
})

After the above request returns a response, data now looks like this:

data = {
  me: {
    email: '[email protected]',
    name: 'Email Email'
  }
}

And then in the main.js file I implement vue-router and my app is then bootstrapped. It renders my side navigation and other components, and in the middle there is a <router-view></router-view> for the main content.

Ex (app.html rendered from main.js):

<div is="navigation"></div>
<router-view></router-view>

In my navigation component, and furthermore my components rendered by the vue-router, how can I access data that I want to be global, for example me which is set in the root component?

I want to be able to access data like the user's e-mail and name all over the app.

2 Answers 2

7

EDIT:: Check out the new package Vuex - https://github.com/vuejs/vuex . This is designed to be a high-level storage of app data that you can access from within any component. This is definitely the best option now.

Original answer:


A few options that I can think of:

1) pass the current user data to each component that needs it. This would be a bit annoying but maintains the principle that a component should not need any outside information to perform its function.

2) use this.$parent to move up the component chain to the root component, where you will be able to access the data you need.

3) just make a global variable. Declare it outside the scope of Vue and have access to it wherever you want.

Sign up to request clarification or add additional context in comments.

2 Comments

For option one, you're talking pass it as a prop? For options two, I tried this, but data is undefined on $parent. Could it be because it isn't set until the response from the HTTP request sets it? Seems like option 2 would be the best which I've tried but logging it in the console is returning undefined.
Please see edit @Noah, there is a new package from the creator of Vue that is specifically meant for this purpose.
1

$root works for me. At each level of components hierarchy, it refers to the root data.

For example you are inside a component and a sub component needs email, you can do this to access the email:

$root.me.email

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.