【问题标题】:Bind the vue to root element after plugin finishes ajax call插件完成ajax调用后将vue绑定到根元素
【发布时间】:2017-11-14 17:34:31
【问题描述】:

我正在将我的应用程序根元素#app 绑定到 vue,在此之前我正在使用 Vue.use(myplugin) 加载我的自定义插件。我的插件进行了 ajax 调用,加载数据并将其设置为 Vue.$permission 属性.. 所以简而言之,我想在安装应用程序之前加载我的用户权限。但是当我的 ajax 调用正在获取权限数据时,应用程序已安装并且我的页面正在呈现,这需要权限对象。

有没有办法在我的插件完成后将应用程序根元素绑定到 vue.. 或任何其他替代解决方案?

【问题讨论】:

    标签: javascript plugins vue.js


    【解决方案1】:

    是的,其实很简单:

    const Vue = require('vue');
    
    const vueInstance = new Vue({
        // don't specify the 'el' prop there
    });
    
    doingAnAjaxCall() // assuming it returns a promise
        .then(() => {
            vueInstance.$mount('#root'); // only now the vue instance is mounted
        });
    

    如果 Vue 实例在实例化时没有收到 el 选项,它将处于“未安装”状态,没有关联的 DOM 元素。 vm.$mount() 可用于手动启动未挂载的 Vue 实例的挂载。

    见:https://vuejs.org/v2/api/#vm-mount

    因此,对于您的情况,您可以使用任何异步机制来检测 ajax 调用的结束。也许最简单的解决方案是给你的插件对象传递一个回调函数,然后在里面挂载你的 vue 实例。

     /* Define plugin */
     MyPlugin = {};
     MyPlugin.install = function(Vue, options) {
         doingAnAjaxCall()
             .then(data => {
                 // do something with data
                 options.callback();
             });
     };
    
     const Vue = require('vue');
    
     /* Create the vue instance */
     const vueInstance = new Vue({
         // don't specify the 'el' prop there
     });
    
     /* Install the plugin */
     Vue.use(MyPlugin, { // This object will be passed as options to the plugin install()
         callback: () => {
             vueInstance.$mount('#root'); // only now the vue instance is mounted
         }
     });
    

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2012-12-15
      • 1970-01-01
      • 2021-04-16
      • 2013-02-26
      • 2023-04-07
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多