2017-09-14 161 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/