javascript - VueJS 读取 $root Ajax 从 router-view 中获取数据仅在直接导航到 url 时返回未定义

标签 javascript ajax vue.js vuejs2 vue-router

我正在学习 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/

相关文章:

javascript - 用 <br> 替换\n 无效

javascript - 当事件处理程序附加到父 HTML 元素时,如何防止默认事件操作?

javascript - 使用 Vue 同步 Dygraph

javascript - 如果 Vue 中的语句单击以更改要运行的功能?

vue.js - 传入变量 HTML 的 Vue 插槽

javascript - 使用 Javascript 循环遍历并从 JSON 表示法中提取项目值

javascript - 如何解析 GraphQL 中的嵌套类型?

javascript - 光滑 slider 中心模式不起作用

javascript - jqGrid:在表中已有本地数据后加载 JSON 数据

javascript - HTTP PUT 的目的是什么?