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

问题描述 投票:24回答:4

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

vue-router documentation提供了有关如何在导航到每个路由之前和之后加载数据的见解,但我想知道如何在初始页面加载时加载所有路由和页面数据,绕过每次路由加载数据的需要被激活了。

注意,我正在将我的数据加载到acf属性中,然后使用.vuethis.$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,
        } 
    },
}

有任何想法吗?

javascript jquery ajax wordpress vue.js
4个回答
37
投票

我的方法是延迟商店和主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;

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

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


3
投票

在Vue Router的文档中查看此部分

https://router.vuejs.org/guide/advanced/data-fetching.html

因此,首先必须编写从端点获取数据的方法,然后使用观察程序来查看路由。

export default {
    watch: {
        '$route': 'fetchItems'
    },
    methods: {
        fetchItems() {
          // fetch logic
        }
    }
}

由于您正在使用WP Rest API,请随时在Github https://github.com/bedakb/vuewp/blob/master/public/app/themes/vuewp/app/views/PostView.vue#L39上查看我的回购


2
投票

你可以使用navigation guards

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

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,当然。


2
投票

好吧,我终于想出了这件事。我正在做的就是在我的main.js文件中调用同步ajax请求,我的root vue实例被实例化,并为数据属性分配所请求的数据,如下所示:

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文件/组件中的拉取数据,如下所示:

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

最后,我使用以下内容在相同的.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>

要带走的最重要的信息是,所有的ACF数据一开始只被称为ONCE,而每次使用像beforeRouteEnter (to, from, next)这样的路径访问时都是如此。因此,我可以根据需要获得丝般顺畅的页面转换。

希望这可以帮助遇到同样问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.