0

I am building a system that can generate HTML from JSON.

The following JSON

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

Should generate The following html

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

I have made this to convert the JSON

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

The propertie data is the JSON only than parsed to a Object

When I am running this code I get the following error

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

Has anyone any idea of a better solution or a fix to this situation ?

Thank you in advance,

Jeroen

2
  • What if you changed HTMLElement, to new HTMLElement, Commented Mar 3, 2018 at 17:20
  • You should quote HTMLElement, also, arrays don;t have the type & content properties Commented Mar 3, 2018 at 23:53

1 Answer 1

1

You seem to be in need of a recursive function. See the buildElement method below. It is used in the render() and works as you describe:

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.