Implementing Vue components dynamically within a v-for loop based on specific conditions

My JS array is structured like this:

[{type:'text', data: 'some text'},{type: 'image',  data: 'link/to/image'}]

Each value of type corresponds to a different Vue component (<text-block>, <image-block>). I want to use a v-for loop to iterate over this array and dynamically create the appropriate Vue component based on the type.

Most examples of v-for demonstrate creating multiple instances of the same element, such as multiple <li> elements. Is there a method to generate different elements within a v-for loop?

Answer №1

If you want to conditionally render elements, you can simply use the v-if directive:

<div v-for="(item, i) in items" :key="i">
    <text-element v-if="item.type === 'text'"></text-element>
    <image-element v-if="item.type === 'image'"></image-element>
</div>

Another way to achieve the same is by using dynamic components:

<div v-for="(item, i) in items" :key="i">
    <dynamic-component :is="item.type + '-element'"></dynamic-component>
</div>

Just make sure to import the components and define them within the instance.

Answer №2

Imagine if you have an array of movies and you want to display them using Vue.js:

<div id="app">
<ul>
<li v-for="film in films">{{ film }}</li>
</ul>
</div>
<script>

var app = new Vue({

el: '#app',
data: {
  films: ['action movie', 'comedy flick', 'thriller']
}

});

setTimeout(function() {
app.films.push('sci-fi epic');

}, 2000);

</script>

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

The functionality of Selection.modify is unfortunately limited when it comes to input and textarea elements in Firefox

Check out this demonstration (jsfiddle link): const input = document.querySelector('#input'); const textarea = document.querySelector('#textarea'); const div = document.querySelector('div'); const x = (e) => { if (e.ke ...

Guide on adjusting the value for a Bootstrap slider

Using the bootstrap slider, I am trying to configure a way to assign a value to the handle from another variable. Although I came across a method that uses the data-slider-value attribute for this purpose, it did not work for me. <input id="gravite" na ...

Utilize a special JavaScript function to submit a concealed PayPal form

Looking to integrate a call to PayPal within a JavaScript function. The goal is for the PayPal call to occur prior to running myStep1 and myStep2. Check out the function below: function() { // insert PayPal call here, before myStep1 and myStep2 ...

Issues with pagination and navigation in Joomla when using the Swiper JS carousel with Bootstrap 5

Initially, I attempted to incorporate Swiper JS into my Joomla 4 template using Twitter Bootstrap 5. I connected it from CDN. If you visit this link: , you will see the desired layout from a Figma design: Screenshot However, I encountered some issues: A ...

Launch both client and server simultaneously with a single command by utilizing Vue-cli and Webpack

Currently, I am setting up a Vue client with Vue-cli 3 that utilizes Webpack. (To start the client, I run "yarn dev --open") In addition, I am developing a server with an API for the client. (To run the server, I execute "node server/server.js") Is th ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

The jQuery prop method seems to be malfunctioning

Here is the HTML code snippet: <ul class="expander-list" id="category"> <li> <div class="radio" style="padding-left:0px"> <label> <input type="checkbox" id="all" ...

Using JavaScript to consume ASP.net Script Services

My ASP.NET script service needs to be accessed from JavaScript using JSONP due to cross-domain restrictions. When dealing with a complex input structure, I have to construct the client-side input structure myself. How does the matching between the client ...

The file reader feature is currently experiencing issues on both Chrome and Internet Explorer browsers

After uploading an image file from my PC, I convert it to a data URL and then use the img element to preview it. Surprisingly, this process works perfectly fine in Firefox. However, when I try to do the same in Chrome or IE, the src attribute of the img el ...

With a simple click of a button, I aim to have the ability to set a variable to true

I am looking to create a button that changes to true in the Script section. This will allow for a random number to be displayed in the paragraph element. <!doctype html> <html> <button id="button"> random number </button> ...

Consistently encountering errors when trying to install npm

While attempting to install the Search git whodotheyserve. com application, I encountered a persistent error that shows up regardless of what troubleshooting steps I take. I have experimented with different versions of npm, all of which are successfully in ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...

Determine which children should be displayed in a Kendo treeview based on the field titled "ParentId"

After converting a list of records into JSON format, I am looking to transform this data into a hierarchical KendoTreeView. Here is the JSON data: [ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" }, { "id": 2, "name": "B", "parentID": 1, "has ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Encountering the "node:internal/modules/cjs/loader:1050" error while attempting to execute a folder using the "npm run dev" command

I am encountering an issue while attempting to execute a folder using npm run dev, consistently resulting in the same error message. PS C:\Users\My Name\Desktop\My Folder> npm run dev Debugger attached. > <a href="/cdn-cgi/l/e ...

What is the best way to execute a function before showing an alert in a $.post() callback?

Just to clarify, the code I'm working with is not original to me; I am simply making some interface adjustments using a plugin for an existing system. The task at hand involves creating a plugin that utilizes blockUI (yes, a plugin within a plugin) t ...

Vue. Where should this snippet be placed?

After delving into Vue, we were inspired by the concept of a store, which allowed us to separate page state from presentation. We developed an alert component that showcased the content of the alert string stored in store.pageError. As we aimed to incorpo ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

Utilizing Promise and setTimeout in a generator function to develop an asynchronous generator: A comprehensive guide

I am currently working on creating a generator function that produces an async generator. This Generator will yield a deferred value at each time, using promises. The values and their respective delays (in milliseconds) are sourced from two separate arrays ...

Automatically fill in options for up to 3 dropdown menus depending on the choices made in the previous dropdown menu

I've looked through similar questions but haven't found the solution I need. Here's a sample fiddle with some example data for years, months, and days. Instead of manually adding select option divs for each year, I want the div id to dynami ...