VueJS 从父组件访问子组件的数据 [英] VueJS access child component's data from parent
问题描述
我正在为 webpack 使用 vue-cli 脚手架
I'm using the vue-cli scaffold for webpack
我的 Vue 组件结构/层次结构目前如下所示:
My Vue component structure/heirarchy currently looks like the following:
- 应用
- PDF 模板
- 背景
- 动态模板图片
- 静态模板图片
- 降价
在应用程序级别,我想要一个 vuejs 组件方法,它可以将所有子组件的数据聚合到一个可以发送到服务器的单个 JSON 对象中.
At the app level, I want a vuejs component method that can aggregate all of the child component's data into a single JSON object that can be sent off to the server.
有没有办法访问子组件的数据?具体来说,多层深吗?
如果不是,传递可观察数据/参数的最佳做法是什么,以便在子组件修改它时我可以访问新值?我试图避免组件之间的硬依赖关系,因此目前,使用组件属性传递的唯一内容是初始化值.
If not, what is the best practice for passing down oberservable data/parameters, so that when it's modified by child components I have access to the new values? I'm trying to avoid hard dependencies between components, so as of right now, the only thing passed using component attributes are initialization values.
更新:
可靠的答案.在查看了两个答案后,我发现有用的资源:
Solid answers. Resources I found helpful after reviewing both answers:
推荐答案
对于这种结构最好有某种 Store.
For this kind of structure It's good to have some kind of Store.
VueJS 为此提供了解决方案,它被称为 Vuex.如果您还没有准备好使用 Vuex,您可以创建自己的简单商店.
VueJS provide solution for that, and It's called Vuex.If you are not ready to go with Vuex, you can create your own simple store.
让我们试试这个
MarkdownStore.js
export default { data: { items: [] }, // Methods that you need, for e.g fetching data from server etc. fetchData() { // fetch logic } }
现在你可以在任何地方使用这些数据,导入这个 Store 文件
And now you can use those data everywhere, with importing this Store file
HomeView.vue
import MarkdownStore from '../stores/MarkdownStore' export default { data() { sharedItems: MarkdownStore.data }, created() { MarkdownStore.fetchData() } }
如果您不想使用 Vuex,这就是您可以使用的基本流程.
So that's the basic flow that you could use, If you dont' want to go with Vuex.
这篇关于VueJS 从父组件访问子组件的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- PDF 模板