Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then delivered to the front-end through the API.

The format of the API output might resemble something like this:

{content: [
  {component: hero, content: {...} },
  {component: form, content: {...} },
  ...
]}

To generate related content, my initial thought is to utilize dynamic components like:

<template v-for="item in content">
  <component :is="item.component" />
</template>

However, I realize that I will need to somehow add properties data to these components, which does not seem to be explicitly described in the Vue documentation. This raises the question of how to pass props to dynamic components that have completely different sets of props (for example, a hero component might require an image while a form component may need input placeholders) - any suggestions?

Answer №2

It has become imperative to specify the version of Vue you are using in your projects.

For Vue 2, you can achieve this by following the example below:

Vue.component('FirstComponent', {
  props: ['title', 'prop1_1'],
  template: `
    <div>
      {{ title }}<br />
      {{ prop1_1 }}
    </div>
  `
})

Vue.component('SecondComponent', {
  props: ['title', 'prop2_1', 'prop2_2'],
  template: `
    <div>
      {{ title }}<br />
      {{ prop2_1 }}<br />
      {{ prop2_1 }}
    </div>
  `
})

new Vue({
  el: "#app",
  data() {
    return {
      items: [
        {
          component: 'FirstComponent',
          props: {
            title: 'First component title',
            prop1_1: 'this is prop 1_1'
          },
        },
        {
          component: 'SecondComponent',
          props: {
            title: 'Second component title',
            prop2_1: 'this is prop 2_1',
            prop2_2: 'this is prop 2_2',
          },
        },
      ]
    }
  },
  template: `
    <div>
      <component
        v-for="(item, idx) in items"
        :key="idx"
        :is="item.component"
        v-bind="item.props"
      ></component>
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></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

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

What is the best way to utilize variables in order to style this image inside a selector?

Struggling with adding dynamic styling to an image inserted into a div through a selector. Despite successful testing of the style changes, I am stuck on how to assign variable values for the properties. Various syntax attempts have failed so far. functi ...

Tips on viewing class object values within the `useEffect` hook

App.js import React, { useRef, useEffect } from "react"; import Token from "./Token"; export default function App() { const tokenRef = useRef(new Token()); useEffect(() => { console.log("current index of token: ", ...

Is there a way to utilize two onChange functions within one component?

I'm having trouble utilizing two onChange functions within the same component. I attempted to combine them, but I ran into an issue because one is using useState and the other is a const function. Below is my code snippet: const signup = () => { ...

Splitting files with Webpack generates dynamic chunk files

Anticipating to only have two distinct chunks named vendors and commons, webpack unexpectedly generates a new chunk file for specific entries with a delimiter. optimization: { splitChunks: { chunks: 'all', cacheGroups: { ...

Issues with jwplayer functionality

After downloading the necessary files and carefully following all instructions, I am still experiencing issues with the player not functioning as expected. <code> <html> <head> <script type="text/javascript" src="/jwpl ...

Clicking on a series in HighCharts will dynamically add a div element

When working with high charts, I encountered an issue where I wanted to create a popup when clicking on each bar using the jQuery balloon popup plugin. Below is the code snippet: plotOptions: { series: { slicedOffset: 0, ...

Dynamic content is loaded on the page using AJAX before refreshing to retrieve new

I am using the FullPage.js plugin and attempting to enable navigation between pages using AJAX. While using .load();, I am able to retrieve the desired page. However, it seems that I need to reload fullpage.js since the loaded page is not active and the s ...

Guide to executing a server-side FUNCTION within a specific namespace room exclusively with the help of socket.io, express, and node.js

I've been developing an online multiplayer game using socket.io, express, and node.js. The server is supposed to detect the number of users connected to a specific room within a namespace and start the game if there are more than two players. However, ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

Instructions on how to set a dynamic parameter within an array when using the computed method and mapState

Hey, I need some help with my computed method: computed: mapState({ aftermovie: (state) => state.festival.aftermovies[id] }), id: { set() { return this.$route.params.id} }, When I try to access the 'id' from the URL ...

Display the retrieved information from MongoDB onto a jade template

Upon checking the console, I see output similar to this: [ { __v: 0, city: 'on1', address: '111', first: 'user', last: 'one', chart: 'char1', doctor: 'doc1', _id: 5698a803d98f05482ba48a4b }, { __ ...

dynamic rendering in React based on the value passed through props

I am attempting to render a component using react.lazy, where the path is a variable in my props. However, I am encountering an error with webpack. The parent component sends the props like this: <DynamicModal url = 'Impuesto/formulario&apo ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

The data is not appearing in the Vuetify data table

I have encountered an issue with the Vuetify data table where it is not displaying any data. Even though it shows that there is 1 row out of 1 displayed, the table body remains empty. Below is my component code: <template> <v-data-table :hea ...

Sending data from a parent component to a child component through a function

In the process of developing an app, I have implemented a feature where users must select options from four dropdown menus. Upon clicking the "OK" button, I aim to send all the selections to a child component for chart creation. Initially, I passed the sel ...

Retrieve the request body in Node.js Express server-side code in order to receive an array passed from the front end

I am facing an issue where I need to save a user's array to mongo. When the data passes through the bridge and reaches the posts, it appears as a strange object with string versions of its indices. I am attempting to convert it back into a normal arra ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

The onChange method in React is failing to execute within the component

I am having trouble overriding the onChange method in a component. It seems like the method is not triggering on any DOM events such as onChange, onClick, or onDblClick. Below are the snippets of code where the component is rendered and the component itsel ...

increasing the efficiency of exporting large amounts of data in Laravel to prevent timeout errors

I need to create a monthly report based on a database containing thousands of records. Sometimes, users may request reports spanning multiple months. With the current record size, a month's worth of data can exceed 5000 entries. Currently, I am utili ...