As I familiarize myself with vuejs, I decided to challenge myself by creating a webpage similar to an eshop for practice purposes.
My approach involves fetching all the necessary data in a single api call to ensure easy access from all my router-views for categorization.
The current method I employ is fetching the data on the created
hook of the new Vue
instance and accessing it throughout using $root
.
While this method works well in most cases, issues arise when directly navigating to a URL or refreshing the page.
It appears that the category
object might not be fully loaded, leading to the return of null
.
This seems to be a timing issue, but I have yet to determine the exact placement of components...
My latest attempt at resolving this issue has been through the use of beforeRouteEnter
.
Defined Route:
const routes = [
{ path: '/category/:category', component : category}
]
const router = new VueRouter({
mode: 'history',
routes: routes
})
Router View Component:
const category = {
template: `<div>
<h1>{{$route.params.category}}</h1>
<b>{{category}}</b>
</div>`,
computed: {
vueRoot: function(){
return this.$root;
},
category: function() {
return this.$root.categories.filter(c => c.name === this.$route.params.category)[0]
})
},
}
}
Main Vue Instance:
var app = new Vue({
router,
el: '#app',
data: {
products: {},
groups: {},
categories: {}
},
methods: {
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
},
fetchProducts: function(){
$.get("/api/fetchv2.json", function(data){
console.log(data);
app.products = data.products;
app.groups = data.groups;
app.categories = data.categories;
}).fail(function(error) {
alert( "error" );
console.log(error);
});
}
},
created: function(){
this.fetchProducts();
},
beforeRouteEnter (to, from, next) {
this.fetchProducts();
}
})
Thank you for your assistance in advance!