I have 3 components (get-users, get-projects, get-tasks) - each contains a button which fires an ajax request to retreive some data. I want the data returned from the ajax request to be displayed in a fourth independent component on the page (show-results). e.g.
<div class="row">
<div class="col-md-6>
<get-users></get-users>
<get-projects></get-projects>
<get-tasks></get-tasks>
</div>
<div class="col-md-6>
<show-results></show-results>
</div>
</div>
The get-users component:
<script>
export default {
template: require('./get_users.template.html'),
data: function() {
return {
userList: ''
}
},
methods: {
getUsers(e) {
e.preventDefault();
this.$http.get('api/getusers').then(function (response) {
this.userList = response.data.users; // How can I also pass this to the show-results component?
})
}
}
}
</script>
The Vue instance/decalaration
var Vue = require('vue');
Vue.use(require('vue-resource'));
import getUsers from './components/get_users.vue';
import getProjects from './components/get_projects.vue';
import getTasks from './components/get_tasks.vue';
import showResults from './components/show_results.vue';
new Vue ({
el: '#app',
components: { GetUsers, GetProjects, GetTasks, ShowResults },
})
As the show-results component isn't a part of a parent/child relationship I cant use the $broadcast or $dispatch methods of the API.
Is it possible to pass the data from one component to another at the completion of the ajax promise?
If you need to communicate between parent and child components, pass data through props and emit events from the child component. If you need to communicate between sibling components, create a central piece of state that can be shared between the components that need it.
With Vue 2.0 things are bit different as broadcast has been deprecated. Vue documentation talks about using centralized event bus to accomplish this. Here's how you could it;
Define centralized event hub. So in your The Vue instance/decalaration define
const eventHub = new Vue() // Single event hub
// Distribute to components using global mixin
Vue.mixin({
data: function () {
return {
eventHub: eventHub
}
}
})
Now in your component you can emit events with
this.eventHub.$emit('show-results:users', { users: response.data.users })
And to listen you do
this.eventHub.$on('show-results:users', data => {
// do your thing
})
Use this small plugin if you want to share data between a lot of nested components:
Vue.use(VueGlobalVariable, {
globals: {
user: new User('testuser'),
....
},
});
use $user
in any component!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With