仅当直接导航到 url 时,VueJS 读取 $root Ajax 从路由器视图 returns 中获取数据未定义

VueJS reading $root Ajax fetched data from within router-view returns undefined only when directly navigating to url

我正在学习使用 vuejs 的方法,并决定创建一个类似 eshop 的网页进行练习。

我在一次 api 调用中获取所有数据,并希望从我的所有路由器视图中访问它们,因此我可以将类别名称与其余数据配对。

我目前所做的是在 new Vue created 上获取我的所有数据,然后使用 $root.

从所有路由器视图相应地访问它

这很好用,除非直接导航到 url 或刷新页面。

据我所知,category 对象似乎尚未加载并且 returns null

这显然是一个时间问题,但我还没有设法找到需要去哪里...

beforeRouteEnter 是我解决这个问题的最新尝试

我的路线

const routes = [
        { path: '/category/:category', component : category}
    ]

    const router = new VueRouter({
        mode: 'history',
        routes: routes
    })

路由器视图

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();
        }
    })

提前致谢

类别组件中的计算值将在类别组件实例化时尝试运行。由于您的数据是异步检索的,这意味着在从服务器检索数据之前,计算将尝试 filter 一个空对象(因为这就是 categories 的初始化方式)。

相反,使用空数组 [] 初始化 categories