Guide on setting up and duplicating a template in Vue.js

Allow the user to create multiple person entries by clicking a button with the method "useIt()". A template has been created for this purpose. When the button is clicked, the template should be duplicated and added to the container div. This functionality has been tested in jsfiddle and it works correctly. However, after copying it into my Vue application, it no longer functions. There are no error messages or warnings, it simply does not work. What could be causing this issue?

Here is the link to the functionality on jsfiddle: http://jsfiddle.net/4vuae12j/1/

 <template>
      <div class="content_modal noShadow modul">
        <div class="modal-header modul_header">
          <h3 class="modul_title">{{ title }}</h3>
        </div>
    
    
        <div class="body">     
    
          <!-- Person Data -->
          <testmodul1></testmodul1>
    
          <!-- Degree -->
          <testmodul2 title="2 Degree"></testmodul2>
        </div>
    
        <button @click="useIt()">
          Use me
        </button>
        <div id="container"></div>
    
        <template id="temp">
          <div>
            <label>Firstname</label>
            <input type="text"/>
            <label>Lastname</label>
            <input type="text"/>
          </div>
        </template>
      </div>
    </template>
    <script>
    
        //Load Modules
        let testmodul1 = Vue.defineAsyncComponent(() =>
          loadModule("./components/1_1_Module_Person.vue", options)
        );
        let testmodul2 = Vue.defineAsyncComponent(() =>
          loadModule("./components/2_Module_Degree.vue", options)
        );
        
        export default {
          data() {
            return {
              title: "Title",
            };
          },
          components: {
            testmodul1: testmodul1,
            testmodul2: testmodul2,
          },
          methods:{
            useIt(){
              console.log("##########CLICKED##########");
              var content = document.querySelector('#temp').content;
              console.log(content);
              document.querySelector('#container').appendChild(
              document.importNode(content, true));
            }
          }
        };
        </script>

Answer №1

If you want to utilize a v-for loop, here's an example of how you can do it:


<div v-for="item in items" :key="item.id">
  <div>
    <label>Name</label>
    <input type="text"/>
    <label>Age</label>
    <input type="text"/>
  </div>
</div>

To make this work correctly, make sure to update your click event like so:

methods: {
  addItem() {
    this.items.push({
      id: this.id += 1;
    })
  }
}

data() {
  return {
    id: 0, 
    items: [{   
      id: 0, 
    }],
  }
}

By clicking the button, you will add a new item defined in your template. Additionally, each click will generate a unique ID for easier future modifications.

I hope this explanation assists you!

Tip: Leveraging Vue.js features like v-for, v-model, and v-if is more efficient than relying on jQuery for similar functionalities.

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

Why does updating child data in Vue 3 affect the parent component?

When looking at this example... <template> <h2>Parent</h2> {{ parent.a }} {{ parent.b }} <ChildComponent :data="parent" /> </template> <script setup> import { reactive } from 'vue' im ...

To add a stencil component via NPM, please note that its functionality cannot be directly accessed within react.js and vue.js

My goal is to implement the stencil component method in both React.js and Vue.js, but I am encountering difficulties with this approach. The method is defined using @METHOD in stencil.js. Here is the code snippet: In React.js <li-rating ref={this.liRa ...

The Disabled element does not exhibit effective styling

When we include the disabled attribute in the text element, the style does not work. Can you explain why? <input pInputText [style]="{'padding-bottom':'10px','padding-top':'10px','width':'100%&apos ...

Align text vertically above and below an input field labeled using tailwindcss

I am striving to achieve the desired outcome but with the text in front of the input vertically aligned with the text after the input. https://i.sstatic.net/0WTfk.png Here is what I have created so far to accomplish that: <div class="space-x-2 fl ...

Implementing a Cancel Button in a Form Using Vue.js Bootstrap-Vue

I am trying to implement a cancel button in my code, similar to the reset button functionality, however, the method is not being triggered and the validation for required fields is still taking place. In my NewUser.vue file, I have added the @cancel="onCa ...

Get rid of the lower padding on a handsontable

I am currently using either Chrome Version 61.0.3163.100 (Official Build) (64-bit) or Safari Version 11.0 (12604.1.38.1.7) on Mac OS Sierra 10.12.6. I am looking to create a handsontable that may exceed the screen height: Click here for an example As I ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

Unable to access the button with Selenium clicking functionality

<button class="css-obkt16-button" type="button"><span class="css-1mhnkuh">Download CSV</span></button> I'm attempting to select the highlighted 'Download CSV' button https://i.sstatic.net/SThoW.png with the HTML code ...

Tips for uploading files in asp.net using an ajax call

I have developed a small asp.net web forms application for managing emails. The interface allows users to input mandatory information such as sender, recipient, and subject. I am now looking to implement file attachments in the emails using the asp.net fil ...

Tips for utilizing ajax function to refresh database entries

I am working with a customer information table that is populated from a database. The last column in this table contains an edit button which, when clicked, shows a popup window with text fields pre-filled with database values. I want users to be able to u ...

A guide on altering the color of a badge through programming

I am curious to learn how I can dynamically change the color of a badge in Angular. My goal is to initially set the color of the badge to white, and then if the percVLRiskTotal reaches a specific value, change the color to green as an example. CSS: <sp ...

Design a dynamic top navigation bar in Angular or any other framework that automatically adjusts to the size of the screen, similar to the responsive bookmarks bar in

Could you offer guidance or suggestions on how to design a navigation bar (using Angular 1, jQuery, CSS, etc) that emulates the functionality of Google Chrome bookmarks bar when resizing the page? Essentially, as the page size decreases, a new button/symbo ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

Explore innovative ways to display mathematical equations dynamically on the browser using NextJS version 13.3.0 or consider alternative solutions for showcasing math content with

I'm currently working on developing a web application that allows users to input LaTeX expressions, which are then dynamically displayed in another div or updated within the same input field. After some experimentation with Mathquill and NextJS v13.3 ...

"Displaying Undefined Content when an Incorrect Value is Added, but functioning correctly with the right

I am attempting to populate the HTML table below with data from a JSON file: When I set var i = "0";, I receive undefined, but changing it to var i = "dv"; results in nothing being displayed. I am uncertain of the error I am making and what is causing th ...

What is the method for obtaining multiple indices on an Array?

Attempting to find multiple index positions in an Array for a Boolean value. Experimenting with while and for loops to iterate through more than one index position without success so far. Below is the code snippet: let jo = [1,2,3,4,5] let ji = [1,2,3] ...

Sharing Variables with $(document).ready

I need help understanding why this code is not functioning and how I can fix it. Despite my efforts to use namespaces and IIFEs, I am still unable to make it work. $(document).ready(function() { alert (hi); }); $(document).ready(function() { var hi = ...

Upon refreshing the page, next.js 13's useSession() function fails to fetch session information

Currently, I am working on replicating an ecommerce site using nextjs 13. On the order page, I am utilizing useSession from next-auth/react to check if a user is signed in or not. Everything works fine when I navigate to the page through a link, but if I r ...

struggling with managing an array of Vue3 refs

Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document. For example, ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...