在组件Vue.js中渲染组件

问题描述 投票:0回答:1

我正在构建一个可以从JSON生成HTML的系统。

以下JSON

"type": "span",
"content": [
  {
    "type": "span",
    "content": [
      {
        "type": "div",
        "content": []
      }
    ]
  }
]

应生成以下html

<span>
 <span>
  <div></div>
 </span>
</span>

我已经做了这个转换JSON

export default {
  name: 'HTMLElement',
  props: {
      data: {
          type: Array,
          default: []
      }
  },
  render(createElement) {
      return createElement(
          this.data.type,
          createElement(
              HTMLElement,
              {
                  props: {
                      data: this.data.content
                  }
              }
          )
      );
  }
}

属性数据是JSON,然后才解析为Object

当我运行此代码时,我收到以下错误

Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

有没有人知道更好的解决方案或解决这种情况?

先感谢您,

吉荣

javascript vue.js components
1个回答
1
投票

你似乎需要一个递归函数。请参阅下面的buildElement方法。它用于render()并按您的描述工作:

Vue.component('html-element', {
  name: 'HTMLElement',
  props: {
    data: {
      type: Object,
      default: {type: 'div'}
    }
  },
  render(createElement) {
    return this.buildElement(createElement, this.data)
  },
  methods: {
    buildElement(createElementFunction, data) {
      return createElementFunction(
        data.type, (data.content || []).map(c => this.buildElement(createElementFunction, c))
      );
    }
  }
});

new Vue({
  el: '#app',
  data: {
    elementData: {
      "type": "span",
      "content": [{
        "type": "span",
        "content": [{
          "type": "div",
          "content": []
        }]
      }]
    }
  }
})
span { display: inline-block; border: 1px solid red; width: 50px }
<script src="https://unpkg.com/vue"></script>

<span>
 <span>
  <div></div>
 </span>
</span>

<hr>

<div id="app">
  <html-element :data="elementData"></html-element>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.