Currently, I am in the midst of a project where I am utilizing Vue.js
for the frontend development. Below is the snippet of code from the main.js
file:
new Vue({ // eslint-disable-line no-new
//el: '#app',
router,
data () {
return {
friends: []
}
},
methods: {
getFriends: function () {
return this.friends;
}
},
created: function () {
this.$http.get('/user/' + this.getUserIDCookie('userID')
+ '/friends').then(function (response) {
this.friends = response.data;
});
},
components: {
'nav-bar': require('./components/Navigation.vue')
},
template: `
<div id="app">
<nav-bar></nav-bar>
<router-view class="router-view"></router-view>
</div>`
}).$mount('#app');
In a specific page scenario(for instance, when redirected to localhost/#/user/1/details
), I'm trying to fetch the list of friends from main.js
as shown below:
<script type="text/babel">
export default {
name: 'profile',
data: function () {
return {
user: {},
friends: []
}
},
methods: {
// Some methods
},
created: function () {
this.friends = this.$root.getFriends();
}
}
</script>
An issue arises when I refresh the current page. Following the refresh, this.friends
ends up being null or undefined as this.$root.getFriends()
returns null/undefined. While I can relocate it to the user
component, my preference is to retain it in main.js
so that the GET
call is executed once and the data remains accessible throughout the application.
If you have any suggestions on how to address this complication, please do share your insights. The version of Vue being used is 2.0.1