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

100*_*ols 30 javascript ajax wordpress jquery vue.js

我目前正在使用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')
Run Code Online (Sandbox Code Playgroud)

Home.vue组件代码:

export default {
    name: 'about',
    data () {
        return {
            acf: this.$parent.acfs,
        } 
    },
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 47

我的方法是延迟商店和主Vue的构建,直到我的AJAX调用返回.

store.js

import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';

Vue.use(Vuex);

function builder(data) {
  return new Vuex.Store({
    state: {
      exams: data,
    },
    actions,
    getters,
    mutations,
  });
}

export default builder;
Run Code Online (Sandbox Code Playgroud)

main.js

import Vue from 'vue';
import VueResource from 'vue-resource';
import App from './App';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

Vue.use(VueResource);

Vue.http.options.root = 'https://miguelmartinez.com/api/';

Vue.http.get('data')
  .then(response => response.json())
  .then((data) => {
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store: store(data),
      template: '<App/>',
      components: { App },
    });
  });
Run Code Online (Sandbox Code Playgroud)

我已经将这种方法与其他框架一起使用,例如Angular和ExtJS.

  • 这非常聪明. (3认同)
  • 如果您不想使store为构建器,则只要您的ajax承诺得以解决,就可以调用store.commit('set_exams',data)`。假设您要进行相关的变异。 (3认同)

tsi*_*orn 6

我根据对这篇文章的所有精彩回复编写了自己的版本……几年过去了,也给了我更多的工具。

main.js中,我使用 async/await 调用预取服务来加载启动时必须存在的任何数据。我发现这增加了可读性。获得数据通讯后,我将其分派到 beforeCreate() 挂钩中相应的 vuex 存储模块。

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

import { prefetchAppData } from '@/services/prefetch.service';

(async () => {
    let comms = await prefetchAppData();

    new Vue({
        router,
        store,
        beforeCreate() {
            store.dispatch('communityModule/initialize', comms);
        },
        mounted() {},
        render: h => h(App)
    }).$mount('#app');
})();
Run Code Online (Sandbox Code Playgroud)

我觉得有必要警告那些人要小心你预取的内容。尝试谨慎执行此操作,因为它确实会延迟初始应用程序加载,这对于良好的用户体验来说并不理想。

这是我的示例prefetch.service.js,它负责数据加载。这当然可以更复杂。

import api from '@api/community.api';
export async function prefetchAppData() {
    return await api.getCommunities();
}
Run Code Online (Sandbox Code Playgroud)

一个简单的 vue 商店。该商店维护应用程序启动之前需要加载的“社区”列表。

Community.store.js(注意我使用 vuex 模块)

export const communityModule = {
    namespaced: true,
    state: {
        communities: []
    },
    getters: {
        communities(state) {
            return state.communities;
        },
    },
    mutations: {
        SET_COMMUNITIES(state, communities) {
            state.communities = communities;
        }
    },
    actions: {
        // instead of loading data here, it is passed in 
        initialize({ commit }, comms) {
            commit('SET_COMMUNITIES', comms);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)


min*_*gos 5

您可以使用导航守卫

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

export default {
    beforeRouteEnter (to, from, next) {
        // my ajax call
    }
};
Run Code Online (Sandbox Code Playgroud)

您还可以为所有组件添加导航守卫:

router.beforeEach((to, from, next) => {
    // my ajax call
});
Run Code Online (Sandbox Code Playgroud)

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

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

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


100*_*ols 5

好吧,我终于弄清楚了这个问题。我所做的就是在main.js实例化根 vue 实例的文件中调用同步 ajax 请求,并为请求的数据分配一个数据属性,如下所示:

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')
Run Code Online (Sandbox Code Playgroud)

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

export default {
    name: 'app',
    data () {
    return {
        acf: this.$parent.acfs,
    }
},
Run Code Online (Sandbox Code Playgroud)

.vue最后,我使用以下内容在同一模板中渲染数据:

<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>
Run Code Online (Sandbox Code Playgroud)

最重要的信息是,所有 ACF 数据在一开始只被调用一次,而不是每次使用类似beforeRouteEnter (to, from, next). 因此,我能够根据需要获得丝般平滑的页面过渡。

希望这对遇到同样问题的人有所帮助。