[Vuejs]-Generate HTML with Tag from provided data json/array

0👍

Vue.js render function should meet your requirement. Using it you can recursively traverse the array, creating all DOM elements. Please take a look a the demo:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#demo',
  data () {
    return {
      items: [
        {
          id: 6568,
          tag: 'h1',
          mesg: '1',
          child: [
            {
              id: 6569,
              tag: 'h2',
              mesg: 11,
              child: [
                {
                  id: 6570,
                  tag: 'h4',
                  mesg: '111',
                  child: []
                }
              ]
            },
            {
              id: 99777,
              tag: 'p',
              mesg: 1123
            }
          ]
        },
        {
          id: 56565,
          tag: 'p',
          mesg: '6568985',
          child: []
        }
      ]
    }
  },
  render: function (createElement) {
    const renderNode = item => {
      const children = [item.mesg];
      if (item.child && Array.isArray(item.child)) {
        children.push(...item.child.map(renderNode))
      }
      return createElement(item.tag, children)
    }
    return createElement('div', this.items.map(renderNode));
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo"></div>

Leave a comment