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@email.com',
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.
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.
$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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.