简体   繁体   中英

How to get value from the Child component of another Parent in Vue js?

I have Component A and It has 2 child components C1 and C2. Into the C1 component, there is a function with which one is getting data from a source same in C2. For C1

 <template> </template> <script> export default { url = 'abc.com'; name: 'c', data () { return { users:'', }}, methods: { getData: function () { $.get(url, function( data ) { this.users = data; var ab = this.users.ab ; var pq = this.users.pq ; )}; }} } </script>

For C2

 <template> </template> <script> export default { url = 'abc.com'; name: 'c', data () { return { users:'', }}, methods: { getData: function () { $.get(url, function( data ) { this.users = data; var cd = this.users.cd ; var rs = this.users.rs ; )}; }} } </script>

AND I have another component D

 <template> </template> <script> export default { data () { return { }}, methods: { showDataABCD: function () { // here I want to access all data of users object of C1 and C2] // especially ab, cd }, showDataPQRS: function () { // here I want to access all data of users object of C1 and C2 //especially PQ, RS } } </script>

Within this D component, I need to access objects of those two components. Can I use state or any other possible way ?

There are plenty ways of achieving your goal.

  • you could just give every child component a "ref=..." and access them directly from parent. (assuming A is a child of D)
  • you can commit the answer of the http requests to the state
  • you can emit an event upwards to the parent component with the data as parameter and store it (assuming A is a child of D)
  • you can use eventbus to pass the data from children to their parent

However, if you want to trigger the search from component D, you might want to add an custom-event-listener (eventbus.$on...) on C1 and C2 in the first place. (you could pass a callback function too)

You could adapt the pattern I described here Vue.js edit variables in dynamic components

Just pass the objects you want to share as props from the parent. Then, as the children emit updated data, let the parent set it and the data flow down to its children with the "shared state".

The data would flow parent -> child -> child update -> parent receives update -> all children updated.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM