vuejs读取$ root ajax从路由器视图中获取数据仅在直接导航到URL时返回未定义



我正在学习围绕vuejs的方式,并决定创建一个类似eShop的网页进行练习。

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

我目前要做的是在new Vue created上获取所有数据,然后从所有路由器视图中访问$root

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

从我能找到的东西来看,category对象似乎尚未加载并返回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]
                })
            },
        }
    }

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

预先感谢

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

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

最新更新