Populate Vue components dynamically without the need for additional frameworks like Nuxt in Vue3

My goal is to develop a checksheet application using Vue, where the tasks are specified in an excel file.

=====

  1. To start, task A needs to be completed.

  2. Followed by task B.

and so on...

=====

I am considering creating a CheckItem.vue component for each task. It will have the following structure:

<template>
  <div :class="[isChecked ? 'task-styling' : 'task-styling-checked']">
    <div class="task-text">Perform task A.</div>
    <img class="task-image" alt="Task 1" src="../assets/img001.png" />
    <div class="check-button">
      <button
        @click="changeColor"
        type="submit"
        class="check-buttom"
      >
        Check
      </button>
    </div>
  </div>
</template>

My objective is to utilize the same "CheckItem.vue" component for all tasks listed, but customizing the "task-text" and "task-image" with relevant data.

Currently, I am open to manually hard code these fields (with plans to optimize this process later). I simply need guidance on how to dynamically insert different data into the same component.

Answer №1

Check out the code snippet below to learn how to create dynamic components in VueJS using a loop through your data object with the v-for directive and passing props:

const App = {
  data() {
    return {
      tasks: [{id: 1, text: 'aaa', img: 'https://picsum.photos/30/29'}, {id: 2, text: 'bbb', img: 'https://picsum.photos/30/30'}, {id: 3, text: 'ccc', img: 'https://picsum.photos/30/31'}]
    }
  }
}
const app = Vue.createApp(App)
app.component('CheckItem', {
  template: `
    <div :class="isChecked ? 'task-styling-checked' : 'task-styling'" class="task">
      <div class="task-text">{{ task.text }}</div>
      <img class="task-image" alt="Task 1" :src="task.img" />
      <div class="check-button">
        <button
          @click="changeColor"
          type="submit"
          class="check-buttom"
        >
          Check
        </button>
      </div>
    </div>
  `,
  props: ['task'], //👈
  data() {
    return {
      isChecked: false
    }
  },
  methods: {
    changeColor() {
      this.isChecked = !this.isChecked
    }
  }
})

app.mount("#demo");
.task-styling {
  background: skyblue;
}
.task-styling-checked {
  background: peru;
}
.task {
  padding: 1em;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="demo">
  <div v-for="item in tasks" :key="item.id"> <!-- 👈 -->
    <check-item :task="item"></check-item>
  </div>
</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

Show real-time server responses using jQuery while waiting for the AJAX request to complete

I have a challenge in creating a function that displays the server response while waiting for Ajax to complete. Here's the scenario: I have selected 10 checkboxes. When I click the submit button, Ajax is triggered. On the server side, there is a loo ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Ways to disable mousewheel function in jQuery

I am trying to deactivate the mouse scroll in jQuery and successfully did so, however, I encountered this error message jquery.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See Thi ...

Error: The MUI Popper Component constantly closes when re-rendering due to props issue

I have been exploring how to structure a component incorporating MUI's Popover component, especially when dealing with dynamic props being passed to a controlled Slider component inside the Popover as well as the anchor element being updated dynamical ...

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Steps for ensuring a div component appears on top of any other component (like h1 or p)

The outcome of the code below is displayed in this image: https://i.stack.imgur.com/CPDqC.png Is it possible to make the dropdown overlap on top of the 'HELLO's text, hiding the h1 and p tags? I have tried using z-index without success. Making ...

What is the best way to extract user input and pass it to an AJAX request URL?

Recently, I successfully completed an AJAX request using AngularJS. You can check out the code here. Everything was working perfectly until I tried to add a dynamic variable (city) to the link like this: $http.get('http://api.wunderground.com/api/KEY ...

The attribute 'sandwiches' cannot be found within the data type 'string'

In my app, I require an object that can store strings or an array of strings with a string key. This object will serve as a dynamic configuration and the keys will be defined by the user, so I cannot specify types based on key names. That's why I&apos ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...

Divide data into an HTML table and merge it with header information

My HTML form contains an interactive HTML table where users can add/delete rows. I am sending this data to a Google Sheet and need to store the row information with corresponding header details. Each time a user submits the form, a new row is added to the ...

The sticky navigation bar isn't functioning properly, even though the code worked perfectly on W3School

I recently encountered an issue while trying to create a sticky navbar that would remain fixed after scrolling past a certain point. I found and customized some code from w3schools that included an animation effect, and it worked perfectly in their demo. H ...

Utilizing an external API in Javascript for fetching data

Is it permissible for me to directly initiate an API request from JavaScript to an external API (in this scenario at ) using the XMLHttpRequest object? If not, what steps should I take to retrieve data from this source? Do I need to incorporate a PHP bac ...

What could be the reason behind my Heroku app suddenly crashing without any visible errors?

After successfully starting the Nest application, about 50 seconds later it transitions from 'starting' to 'crashed'. The last log entry before the crash is a console log indicating the port number. View Heroku logs after successful bui ...

Error encountered during Nuxt build: Syntax error on Line 1 of the SCSS component file

I'm currently working on a project in node 18.7.0 that utilizes nuxt 2.15.8. Within my Vue component, I have the following SCSS code: <style lang="scss"> .Accordion { --Accordion__margin-top: 2.5rem; &__items { margin ...

The script fails to execute on content loaded through AJAX in Django

I have a website with nested div elements that make up a complete set. These elements can be dynamically loaded when the user clicks the "load more" button. The website includes a script that changes the style of the aforementioned div element when the pa ...

JavaScript has the ability to manipulate the width of an element by using methods to both retrieve

I have a unique situation where I need to dynamically adjust the width of a ul list element based on the text content inside it. Specifically, I want the width of the ul list to be equal to the width of the first list item, which can change frequently. My ...

`problem with moment.js incorrectly identifying the day of a given date`

I'm currently working with a field that has the value 03-01-2020, which is in the DD-MM-YYYY date format. However, when I apply the code moment.utc(document.getElementById('date').value, "DD-MM-YYYY HH:mm:ss").toDate(), I noticed that the re ...

Using JavaScript to make an asynchronous call to the server via AJAX

Is it true that clients can block JavaScript in their browsers? If so, what impact does it have on AJAX calls - do they still function properly? ...