I'm learning my ways around vuejs and decide to create an eshop-like webpage for practice.
I fetch all my data in one api call and want to have access to them from all my router-views, so I can pair the category name to the rest of the data.
What I currently do is fetch all my data on the new Vue created and then access it accordingly from all the router-views with $root.
This works great except when directly navigating to the url or refreshing the page.
From what I could find, it seems the category object is not yet loaded and returns null
This is obviously a timing issue, but I have not managed to find what needs to go where...
The beforeRouteEnter was my latest attempt to fix this issue
My route
const routes = [
{ path: '/category/:category', component : category}
]
const router = new VueRouter({
mode: 'history',
routes: routes
})
Router View
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
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();
}
})
Thanks in advance
categories: {})? Objects do not have afiltermethod.