2017-06-20 42 views
0

有没有什么方法可以在组件内设置/覆盖插槽的内容?像Vue.js - 以编程方式设置插槽内容

模板:

<div> 
    <slot></slot> 
</div> 

JS:

export default { 
    ... 
    mounted() { 
     this.$slot.render("<button>OK</button>"); 
    } 
    ... 
} 

我知道我可以在我的元素来动态地将内容推到组件模板上使用v-html,但我的意思不只是纯HTML我的意思是HTML用Vue指令。像:

JS:

export default { 
    ... 
    mounted() { 
     this.$slot.default.render('<button @click="submit">OK</button>'); 
    }, 
    methods: { 
     submit() { 
      // Here I want to get :) 
     } 
    } 
    ... 
} 

基本上我想Vue的渲染(如解析和渲染,而不是像innerHTML)在我的组件的范围一定的字符串,并把在某一点在我的组件。原因是我通过AJAX从服务器获取新内容。

对不起,但在Google搜索2天后,我仍然无法找到我的头。

非常感谢!

+0

大概不会。您最好的机会是在创建实际对象之前构建组件模板字符串(但不支持任何更改)。这是一个非常糟糕的解决方案,所以你很可能应该考虑重构你的应用程序。 – Cobaltway

+0

感觉有点像对框架的工作 – keksnicoh

回答

0

我认为这是您最好的机会:即时创建您的组件。 在这个例子中,我使用了一个简单的占位符(用v-cloak)。

使用vue-router可以在执行过程中添加新创建的组件,使用router.addRoutes,您可以获得更好的结果,因此您的应用程序无需等待实例化整个vue。

function componentFactory(slot) { 
 
    return new Promise((resolve, reject) => { 
 
    window.setTimeout(() => { // Asynchronous fetching 
 
     resolve({ // Return the actual component 
 
     template: `<div> 
 
      ${slot} 
 
      </div>`, 
 
     methods: { 
 
      submit() { 
 
      console.log('hello'); 
 
      } 
 
     } 
 
     }); 
 
    }, 1000); 
 
    }); 
 
} 
 

 
componentFactory('<button @click="submit">OK</button>') // Build the component 
 
    .then(component => { 
 
    new Vue({ // Instantiate vue 
 
     el: '#app', 
 
     components: { 
 
     builtComponent: component 
 
     } 
 
    }); 
 
    });
[v-cloak], .placeholder { 
 
\t display: none; 
 
} 
 

 
[v-cloak] + .placeholder { 
 
\t display: block; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script> 
 

 
<div id='app' v-cloak> 
 
    <built-component></built-component> 
 
</div> 
 
<div class="placeholder"> 
 
    This is a placeholder, my vue app is loading... 
 
</div>

相关问题