Vue.js从子组件访问父/根数据 [英] Vue.js access parent/root data from a child component
问题描述
我的 main.js
文件引用 #app
作为 el
,然后在 ready
它向我的API发送HTTP请求,以根据从 localStorage中获取的令牌获取用户数据
。
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);
})
在上述请求返回响应后, data
now看起来像这样:
After the above request returns a response, data
now looks like this:
data = {
me: {
email: 'email@email.com',
name: 'Email Email'
}
}
然后在 main.js
文件中,我实现了 vue-router
,然后我的应用程序被引导。它呈现我的侧面导航和其他组件,中间有一个< router-view>< / router-view>
作为主要内容。
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
从 main.js
呈现):
<div is="navigation"></div>
<router-view></router-view>
在我的导航组件中,此外我的组件由 vue-router呈现
,如何访问我想要全局的数据,例如 me
哪个在根组件中设置?
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.
推荐答案
:查看新软件包Vuex - https://github.com/vuejs/vuex 。这是一个可以从任何组件中访问的应用程序数据的高级存储。这绝对是现在最好的选择。
: 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.
原始答案:
我能想到的几个选项:
1)将当前用户数据传递给需要它的每个组件。这会有点烦人但保持一个组件不需要任何外部信息来执行其功能的原则。
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)使用这个。 $ parent
将组件链向上移动到根组件,在那里您将能够访问所需的数据。
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)制作一个全局变量。将其声明在Vue的范围之外,并且可以随时随地访问它。
3) just make a global variable. Declare it outside the scope of Vue and have access to it wherever you want.
这篇关于Vue.js从子组件访问父/根数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!