从REST API响应中呈现自定义标记

时间:2017-09-14 04:48:55

标签: javascript vue.js vue-component

我有以下组件MyComponent.vue:

<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是我从REST API获得的html-string。例如:

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

custom-component标签未在5种情况下呈现。

是否可以从html-string渲染vue组件,这是从REST API获得的,如果我在v-html中使用此字符串?

1 个答案:

答案 0 :(得分: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/