我正在学习 vuejs 的方法,并决定创建一个类似 eshop 的网页进行练习。
我在一次 api 调用中获取所有数据,并希望从所有路由器 View 访问它们,这样我就可以将类别名称与其余数据配对。
我目前所做的就是获取 new Vue
上的所有数据created
然后从所有路由器 View 中使用 $root
相应地访问它.
除非直接导航到 URL 或刷新页面,否则这非常有效。
据我所知,似乎category
对象尚未加载并返回 null
这显然是一个时间问题,但我还没有找到需要去哪里的东西......
beforeRouteEnter
这是我解决此问题的最新尝试
我的路线
const routes = [
{ path: '/category/:category', component : category}
]
const router = new VueRouter({
mode: 'history',
routes: routes
})
路由器 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]
})
},
}
}
主视图
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();
}
})
提前致谢
最佳答案
类别组件中的计算值将在类别组件实例化时尝试运行。由于您的数据是异步检索的,这意味着在从服务器检索数据之前,计算将尝试过滤
一个空对象(因为这就是categories
的初始化方式) .
相反,使用空数组[]
初始化类别
。
关于javascript - VueJS 读取 $root Ajax 从 router-view 中获取数据仅在直接导航到 url 时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856586/