如何在初始vue.js / vue-router加载时加载所有服务器端数据?

JavaScript

2020-03-12

我目前正在使用WordPress REST API和vue-router在小型单页站点上的页面之间进行转换。但是,当我使用REST API对服务器进行AJAX调用时,数据将加载,但仅在页面已呈现之后才加载。

VUE路由器文档提供了深入了解在关于如何前和导航到各航线后加载数据,但我想知道如何加载在初始页面加载的所有路线和页面数据,绕过需要每个负载数据激活路线的时间。

请注意,我正在将数据加载到acf属性中,然后使用来在.vue文件组件中访问它this.$parent.acfs

main.js路由器代码:

const router = new VueRouter({
    routes: [
        { path: '/', component: Home },
        { path: '/about', component: About },
        { path: '/tickets', component: Tickets },
        { path: '/sponsors', component: Sponsors },
    ],
    hashbang: false
});

exports.router = router;

const app = new Vue({
    router,
    data: {
        acfs: ''
    },
    created() {
        $.ajax({
            url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
            type: 'GET',
            success: function(response) {
                console.log(response);
                this.acfs = response.acf;
                // this.backgroundImage = response.acf.background_image.url
            }.bind(this)
        })
    }
}).$mount('#app')

Home.vue组件代码:

export default {
    name: 'about',
    data () {
        return {
            acf: this.$parent.acfs,
        } 
    },
}

有任何想法吗?

第918篇《如何在初始vue.js / vue-router加载时加载所有服务器端数据?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Sam神乐番长 2020.03.12

您可以使用导航卫士

在特定组件上,它看起来像这样:

export default {
    beforeRouteEnter (to, from, next) {
        // my ajax call
    }
};

您还可以向所有组件添加导航保护:

router.beforeEach((to, from, next) => {
    // my ajax call
});

要记住的一件事是导航保护是异步的,因此您需要next()在数据加载完成后调用回调。我的应用程序中的一个真实示例(保护功能位于单独的文件中):

export default function(to, from, next) {
    Promise.all([
        IngredientTypes.init(),
        Units.init(),
        MashTypes.init()
    ]).then(() => {
        next();
    });
};

在你的情况,你需要调用next()success回调,当然。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android