Reputation: 95
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.
Upvotes: 8
Views: 17962
Reputation: 2583
$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
Upvotes: 1
Reputation: 25221
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.
Upvotes: 7