延迟Vue.JS组件加载,直到承诺得到解决

时间:2018-03-25 16:29:07

标签: javascript asynchronous encryption vue.js libsodium

我在我正在构建的Vue.JS应用程序中广泛使用libsodium.js。 Libsodium.js不能立即使用,它会进行一些异步加载。

因为我在几乎每个.vue组件中都使用这个库,所以我需要在Vue中延迟实际的组件加载,直到libsodium完全加载。

我正在想象这样的事情:

// My root component
const app = new Vue({
    data() {
        return {
            sodium: null
        }
    },
    el: '#app',
    components: { ... },
    router,
    created() {
        const _sodium = require('libsodium-wrappers');
        (async() => {
            await _sodium.ready;
            this.sodium = _sodium;

            // Start loading the vue-router routes (and thus my components) here
            startLoadingComponents();
        })();
    }
});

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

Restructure your code so that the Vue isn't created until sodium is ready.

const _sodium = require('libsodium-wrappers');

function startLoadingComponents(){
  const app = new Vue({
      data() {
          return {
              sodium: _sodium
          }
      },
      el: '#app',
      components: { ... },
      router,
  });  
}

(async() => {
  await _sodium.ready;

  // Start loading the vue-router routes (and thus my components) here
  startLoadingComponents();
  // you could also just really do the new Vue right here...
})();