How to load all server side data on initial vue.js / vue-router load?

后端 未结 5 494
长发绾君心
长发绾君心 2020-11-29 22:42

I\'m currently making use of the WordPress REST API, and vue-router to transition between pages on a small single page site. However, when I make an AJAX call to the server

5条回答
  •  攒了一身酷
    2020-11-29 22:45

    Alright, I finally figured this thing out. All I'm doing is calling a synchronous ajax request within my main.js file where my root vue instance is instantiated, and assigning a data property the requested data as so:

    main.js

    let acfData;
    
    $.ajax({
        async: false,
        url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
        type: 'GET',
        success: function(response) {
            console.log(response.acf);
            acfData = response.acf;
        }.bind(this)
    })  
    
    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: acfData 
        },
        created() {
    
        }
    }).$mount('#app')
    

    From here, I can use the pulled data within each individual .vue file / component like so:

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

    Finally, I render the data within the same .vue template with the following:

    
    

    The most important piece of information to take away, is that all of the ACF data is only being called ONCE at the very beginning, compared to every time a route is visited using something like beforeRouteEnter (to, from, next). As a result, I'm able to get silky smooth page transitions as desired.

    Hope this helps whoever comes across the same problem.

提交回复
热议问题