2017-09-14 103 views
0

呈現自定義標籤,我有以下組成部分MyComponent.vue:從REST API響應

<template> 
    <div v-html="content"></div> 
</template> 

<script> 
    import Vue from 'vue' 
    import CustomComponent from 'CustomComponent.vue' 
    Vue.use(CustomComponent) 

    export default { 
    name: `my-component`, 
    computed: { 
     content() { 
     return this.$store.state.content 
     } 
    }, 

    asyncData({store, route: {params: {id}}}) { 
     // here I fetch 'content' from REST API 
     return store.dispatch('FETCH_CONTENT', {id}) 
    }, 


    // ... 
    } 
</script> 

哪裏this.$store.state.content是HTML的字符串,我從REST API得到。例如:

<custom-component data-count="1"></custom-component><p>some text</p> 

custom-component標籤沒有在5月的情況下呈現。

是否有可能從我從REST API獲得的html-string呈現vue組件,如果我在v-html中使用此字符串?

+0

見https://vuejs.org/v2/guide/components.html#Async - 組件 – Phil

+0

@Phil添加{'custom-component':()=> import('CustomComponent.vue')}並不能解決問題。我認爲它與我在v-html中使用內容相關 –

+0

問題在於你試圖繞過自定義組件的編譯和掛載步驟,這會導致可變性和遵守性方面的更大問題。重新設計系統會更好,以便REST API返回純數據,並且組件將適當地渲染它, –

回答

0

我需要Vue公司版本的編譯器才能使用下面的例子:

<div id="app"> 
    <h3> 
    Vue component creator 
    </h3> 
    Template 
    <textarea v-model="template"></textarea> 
    Options 
    <textarea v-model="options"></textarea> 
    <button @click="create"> 
    Create component 
    </button> 
    <component :is="resultComponent"></component> 
</div> 


Vue.component('test',{ 
    template:'<div>It works!</div>' 
}) 
new Vue({ 
    el:'#app', 
    data(){ 
    return{ 
     stuff:'stuff', 
     template: 
`<div> 
    <test></test> 
    <b>{{stuff}}</b> 
    <div v-for="n in 10">{{n}}</div> 
</div>`, 
      options: 
`{ 
    data(){ 
    return {stuff:'awesome'} 
    } 
}`, 
     resultComponent:undefined 
    } 
    }, 
    methods:{ 
    create(){ 
     let component = new Function('return' + this.options)() 
     component.template = this.template 
     this.resultComponent = component 
    } 
    } 
}) 

小提琴:https://jsfiddle.net/Herteby/9syt27ja/