且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 17:41:28

好的,我终于明白了。我要做的只是在 main.js 文件中调用一个同步ajax请求,在该文件中实例化了我的根vue实例,并为data属性分配请求的数据,如下所示:

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')

从这里,我可以在每个单独的 .vue 文件/组件中使用提取的数据,如下所示:

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,
    }
},

最后,我在同一 .vue 模板,其中包含以下内容:

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

<template>
  <transition
      name="home"
      v-on:enter="enter"
      v-on:leave="leave"
      v-bind:css="false"
      mode="out-in"
    >
    <div class="full-height-container background-image home" v-bind:style="{backgroundImage: 'url(' + this.acf.home_background_image.url + ')'}">
      <div class="content-container">
        <h1 class="white bold home-title">{{ acf.home_title }}</h1>
        <h2 class="white home-subtitle">{{ acf.home_subtitle }}</h2>
        <div class="button-block">
          <a href="#/about"><button class="white home-button-1">{{ acf.link_title_1 }}</button></a>
          <a href="#/tickets"><button class="white home-button-2">{{ acf.link_title_2 }}</button></a>
        </div>
      </div>
    </div>
  </transition>
</template>

最重要的信息是,所有ACF数据都只被调用从一开始就是一次,与每次使用 beforeRouteEnter(到,从,下一个)之类的路径访问相比。结果,我能够按需获得平滑的页面过渡。

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.