Creating nested components in Vue.js

I'm currently working on a project that involves generating HTML from JSON data.

Here is the JSON snippet I am working with:

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

This JSON should result in the following HTML structure:

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

To convert this JSON to HTML, I have created the following code snippet:

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

The 'data' property represents the parsed JSON data as an object.

Unfortunately, when running this code, it triggers the following error message:

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

If anyone has suggestions for a better solution or how to fix this issue, please let me know. Your help is greatly appreciated.

Thank you,

Jeroen

Answer №1

If you find yourself in a situation where you require a recursive function, take a look at the buildElement method provided below. This method is utilized in the render() function and functions exactly as you have described:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to define unique formatters for various transports in Winstonjs?

In order to customize the formatting of console and file transport in Winston, I decided to colorize console logs myself using the chalk module. Below is the code snippet I used to create the logger: this.logger = createLogger({ levels: { fa ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

Closing the Main Dropdown Navbar in Bootstrap 4: What happens once you click on a Menu Option?

How can I close the dropdown menu in the navbar when an option is clicked after it switches to a mobile view? Below is the HTML code for my navbar. <nav class="navbar fixed-top navbar-expand-lg navbar-custom"> <div class="container-fluid"> ...

PHP data is not displayed by Ajax

I seem to be encountering a bit of trouble. I am attempting to utilize ajax to retrieve data from a PHP server, which in turn fetches it from a MySQL database, and then display it within a specific HTML tag location. However, for some unknown reason, nothi ...

The image slideshow on W3 Schools displays images in a stacked formation

Utilizing this code snippet from W3 Schools to incorporate an image slideshow into my web project. However, upon page load/reload, the images appear stacked vertically rather than horizontally (one above and one below). The slideshow functions properly aft ...

What is preventing the onmouseup event from being effective?

In my recent research, I came across some interesting information on mouse-click events from w3schools. According to them, the onmousedown, onmouseup, and onclick events are all crucial parts of a mouse-click process. It starts with the onmousedown event b ...

Can someone show me how to code a function that transforms my paragraph into an image when I hover over it?

< p id="p1" onmouseover="this.style.color='transparent';flipPara()"> < p id="p2" onmouseover="spookyPara()"> function spookyPara() { document.getElementById("p1").attribute = "All_Images/ghost.png"; } I currently have this code sn ...

Searching for a way to detect when a user clicks the back button on their Android or iPhone device using JavaScript or

In the process of building a Single Page Application (HTML5) utilizing the following plugins: - Sammy.js - Knockout.js - Require.js - Jquery.js This app is designed for Android, iPhone, and Windows mobile devices. Many scenarios revolve around cli ...

Using jQuery to decrease the size of a div element containing an image

Hello everyone! I have an image inside a div and I am currently moving it down at a specific time using a delay. My question is, how can I make the image shrink as it moves down the screen until it eventually disappears completely at a set location? Curre ...

Storing a credit card number securely using Stripe in a MERN stack application

Currently, I am working on an application using the MERN stack where users can create companies. Each company requires various details such as name, address, phone number, email, and credit card information including the 16-digit card number, expiration da ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

Utilize the conditional GET method when including scripts through tags in an HTML webpage

Is it possible to benefit from HTTP conditional requests when including a script in the head section of a page? My goal is to cache dynamically downloaded JavaScript files that are added to the head section using script tags. If this approach isn't fe ...

French datepicker encountered an error when trying to set the date

Trying to showcase the datepicker in French, I have included the local's CDN. This is how my code looks: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel=&q ...

Utilizing a c++ xpcom component in conjunction with a javascript xpcom component

After developing an XPCOM component using C++ with a GetHWND() method, I am now working on another XPCOM component using JavaScript. My goal is to utilize the GetHWND function from my C++ component in the JavaScript XPCOM component. Here is the code snippe ...

The v-btn label in Vuetify is extending beyond the lateral borders and overlapping

In this scenario, the button is supposed to break the line and increase its height. However, the text is overlapping the lateral borders (you can see this behavior in the Codepen link provided below). Is there a way to correct this issue? Codepen Link & ...

Utilizing dynamic, MongoDB-inspired expressions to eliminate specific elements from an array

In the process of creating a lightweight database similar to MongoDB, I am incorporating an object-oriented query language where references can be functions or object references: foo.users.find( args ); foo.users.remove( args ); The 'args' para ...

Creating a global variable within nested AJAX requests

I am facing an issue involving nested ajax calls and a global variable. The scenario is that I need to set a globally accessible variable in the success function of one ajax call, which is then called within the success function of another ajax call. The i ...

What is the best way to implement jQuery on an HTML file instead of relying solely on the Document Object Model

My attempt to make modifications to an HTML document has been challenging, as it differs from working with the DOM. I've realized that the syntax I typically use with the DOM doesn't translate well to this other document. For instance, while I co ...