我只是尝试了Vue.js,我正在努力解决将DOM中的信息从一个组件传递到另一个组件的关键概念。
考虑这个示例,其中容器切换按钮应切换容器内的所有组件 ,或者说,将它们全部设置为“true”或“false”。
<div id="app"> <p> <strong>Welcome!</strong> Click the "true/false" buttons to toggle them. Click the "Toggle all" button to toggle them all! </p> <app-toggle-container> <app-toggle></app-toggle> <app-toggle></app-toggle> </app-toggle-container> <app-toggle-container> <app-toggle></app-toggle> <app-toggle></app-toggle> <app-toggle></app-toggle> </app-toggle-container> </div>
在这个代码笔中,我将app-toggle和app-toggle-container为组件: https : //codepen.io/fiedl/pen/mmqLMN?editors = 1010
但我找不到一个好方法将信息从容器传递到单独的切换 。
另外,在第二步中,当尝试反过来时,例如,如果所有切换都为真,则“全部切换”按钮只显示“真”,或者当所有切换都为假时显示“假”,我可以找不到将切换器当前状态的信息传递给容器的方法 。
这似乎不是一个罕见的问题。 在Vue.js中执行此操作的正确方法是什么? 或者我是以错误的方式思考它?
很快,我发现了$broadcast和$dispatch 。 但是当它们被丢弃在Vue.js 2中时,我很可能以错误的方式思考它:)
I'm just trying out Vue.js and I'm struggling with the key concept of passing information up and down the DOM from one component to the other.
Consider this example in which a container-toggle button should toggle all components within the container, or say, set them all to "true" or "false".
<div id="app"> <p> <strong>Welcome!</strong> Click the "true/false" buttons to toggle them. Click the "Toggle all" button to toggle them all! </p> <app-toggle-container> <app-toggle></app-toggle> <app-toggle></app-toggle> </app-toggle-container> <app-toggle-container> <app-toggle></app-toggle> <app-toggle></app-toggle> <app-toggle></app-toggle> </app-toggle-container> </div>In this code pen, I've defined app-toggle and app-toggle-container as components: https://codepen.io/fiedl/pen/mmqLMN?editors=1010
But I can't find a good way to pass the information down from the container to the separate toggles.
Also, in a second step, when trying the other way round, for example, to have the "Toggle all" button just show "true" if all toggles are true, or to show "false" when all toggles are false, I can't find a way to pass the information of the current state of the toggles up to the container.
This doesn't seem like an uncommon problem. What is the proper way to do this in Vue.js? Or am I thinking about this it in the wrong way?
Quickly, I've found $broadcast and $dispatch. But as they are dropped in Vue.js 2, I'm most probably thinking about it in the wrong way :)
最满意答案
我把你的笔分开了http://codepen.io/nicooga/pen/wdPXvJ 。
结果是包含子组件[控制器]的Vue组件的$children属性。 你可以迭代它们并用它们做事。
this.$children.forEach(c => c.toggle());看到
https://vuejs.org/v2/api/#vm-children VueJs Child组件中的Calling方法 。I forked your pen http://codepen.io/nicooga/pen/wdPXvJ.
Turns out theres a $children property for Vue components that contains your children components [controllers]. You can iterate over them and do stuff with them.
this.$children.forEach(c => c.toggle());See
https://vuejs.org/v2/api/#vm-children VueJs Calling method in Child components.更多推荐
发布评论