Vue - 当插件准备好时安装 vue

Kli*_*ick 4 javascript vue.js vuejs2

我制作了一个“OffersPlugin”,在“安装”功能期间从服务器获取一些数据。vue 中加载的第一个组件需要该数据。但在加载 vue 组件之前,http 请求无法完成,而且我没有任何数据可使用。

我怎样才能告诉 vue 在插件准备好之前保持 init vue ?

谢谢。


import Vue from 'vue';

import VueCookie from 'vue-cookie';
import App from './ExampleComponent';

import OffersPlugin from '../plugins/OffersPlugin';


Vue.use(VueCookie);
Vue.use(OffersPlugin);

if(document.getElementById("vue-promotion-edit-section")) {
    new Vue({

        render: h => h(App)
    }).$mount('#vue-promotion-edit-section');
Run Code Online (Sandbox Code Playgroud)

在安装方法中,我有 axios GET 请求。在该请求中,我从服务器加载报价列表。当请求成功时,我将插件变量关联到数组:

const offerList = [];
Run Code Online (Sandbox Code Playgroud)

我使用 getOfferId 方法作为原型。

function(name) 
{
return offersList[name] || 'No offer'
}

Run Code Online (Sandbox Code Playgroud)

Mic*_*evý 7

HTTP 请求本质上是异步的。Vue 初始化本质上是同步的。 您无法通过 Javascript 中的异步操作生成同步结果。

解决方法:

OffersPluginFactory.js:

const pluginFactory = function() {
  let promise = axios.get()
    .then(...process data...)
    // return plugin object with data inside
    .then(data => ({
      install(Vue, options) {
        ...use data here...
      }
    }));
  return promise; // when resolved this promise returns plugin object
}

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

main.vue:

import OffersPluginFactory from '../plugins/OffersPluginFactory';

OffersPluginFactory().then( function(plugin) {
  Vue.use(plugin)

  new Vue({
    render: h => h(App)
  }).$mount('#vue-promotion-edit-section');
} 
);
Run Code Online (Sandbox Code Playgroud)