2017-07-02 57 views
1

中編譯從外部API加載的模板我有一個非SPA網站應用程序,它具有Vue組件,這非常好用。但是,我正在尋找一種通過外部API加載包含Vue的HTML的方法。如何在Vue

所以,我只是做出一個/ajax/dialogbox/client/add呼叫時返回包含Vue組件,如HTML:

<h1>Add client</h1> 
<div>My static content</div> 
<my-component></my-component> 

但顯然<my-component></my-component>沒有做任何事情。 在Angular 1我使用$compile服務在輸出前編譯HTML。

有沒有辦法在Vue做同樣的事情?

回答

2

Vue中有一個compile function可用於編譯模板以渲染函數。使用編譯後的函數需要比您提供的更多的細節(例如,如果您需要將返回的模板與數據一起使用),但下面是一個示例。

console.clear() 
 

 
Vue.component("my-component",{ 
 
    template: `<h1>My Component</h1>` 
 
}) 
 

 
const template = ` 
 
<div> 
 
<h1>Add client</h1> 
 
<div>My static content</div> 
 
<my-component></my-component> 
 
</div> 
 
` 
 

 
new Vue({ 
 
    el: "#app", 
 
    data:{ 
 
    compiled: null 
 
    }, 
 
    mounted(){ 
 
    setTimeout(() => { 
 
     this.compiled = Vue.compile(template) 
 
    }, 500) 
 
    
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 
<div id="app"> 
 
    <component :is="compiled"></component> 
 
</div>

注意,在本例中,我包你的示例模板在div標籤。 Vue要求在Vue或組件的單個根元素上存在。