Currently trying out Vue.js and I must say, it's impressively simpler than Angular. My single page app is utilizing vue-router and vue-resource to connect to my API backend. The primary app.js
loads vue-router and vue-resource along with separate components for each route.
I am faced with a dilemma: How can I utilize props to pass global data fetched through asynchronous AJAX calls to child components? For instance, having the list of users accessible by any child component after fetching the data in the primary app.js
. My goal is to make only one API call for the entire application. Are there alternative solutions I should consider?
Currently, when using props
in the child components, I only receive an empty array initially assigned to the users
variable before the asynchronous AJAX call fetches the actual data. Here's a snippet of the code:
Sample App.js
// Vue setup
// Router map defined
var App = Vue.extend({
ready: function() {
this.fetchUsers();
},
data: function() {
return {
users: [],
};
},
methods: {
fetchUsers: function() {
// Asynchronous AJAX request to fetch users data
}
}
});
// Router initialization
router.start(App, '#app')
Sample app.html
<div id="app" v-cloak>
<router-view users="{{ users }}">
</router-view>
</div>
Sample dashboard.js
module.exports = {
component: {
ready: function() {
console.log(this.users);
},
props: ['users'],
},
};
Upon running dashboard.js
, an empty array is logged to the console due to the initial value set in app.js
. How do I grant access to the updated users
variable from app.js
within dashboard.js
? Your assistance is much appreciated!
p.s. Excluding the usage of inherit: true
as I only want specific app.js
variables available in child components.