VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using document.appendChild for this purpose, but are there any better approaches available?

I currently use a toggle-function which works well, and I have included it in the code below to provide context.

Vue

    Vue.component('dynamicdDvs', {
    template: `

<div>
    <div class="headerDiv">
        <button class="addDiv" type="button" v-on:click="createDiv">Create</button>
    </div>
    <div class="container">
        <div class="createdDiv">
            <h2>I am dynamic!</h2>
            <button class="minimize" v-on:click="expand">Make me smal</button>
        </div>
        <div class="createdDivMinimized" v-if="!displayDiv">
            <p>I am a smal version of the created div!</p>
            <button class="maximize" v-on:click="expand">Expand me</button>
        </div>
    </div>
</div>
`,

  data:function () {
    return {
        displayDiv: false

    }
  },
  methods:  {
        expand: function () {
            this.displayDiv = !this.displayDiv;
        },

        createDiv: function() {
          //The function that creates a new div, with the same code as 
          //.createdDiv and .createDivMinimized may be placed here
        }
    }
});

CSS

.headerDiv {
  height: 100px;
  width: 400px;
  background-color: blue;
  color: white
}

.createdDiv {
  height: 300px;
   width: 400px;
  background-color: black;
  color: white
}

.createdDivMinimized {
  height: 300px;
   width: 400px;
  background-color: red;
  color: white
}

HTML

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="parent">

<dynamicDivs></dynamicDivs>

</div>

Answer №1

If you want to set a specific number of <div> elements in your Vue.js application, you can achieve this by using the v-for with a range method. Here is an example:

data () {
  return {
    displayDiv: [false],
    divs: 1
  }
}

In your template section, you can use the following code:

<template v-for="n in divs">
  <div class="createdDiv">
    <!-- snip -->
    <button class="minimize" v-on:click="displayDiv[n-1] = !displayDiv[n-1]">Make me small</button>
  </div>
  <div class="createdDivMinimized" v-if="!displayDiv[n-1]">
    <!-- snip -->
  </div>
</template>

Additionally, you can include the following method in your script section:

createDiv () {
  this.divs++
  this.displayDiv.push(false)
}

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 function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

Implement the Show/Hide TinyMCE Functionality in your <textarea></textarea> Box

Information I recently added TinyMCE to my website after discovering that a website I frequently visit uses it. While their design and functionality are different, I managed to replicate their look on my own site and now want to implement a specific featu ...

Is the original image source revealed when clicked?

I've implemented an expand and collapse feature using jQuery/JavaScript. Clicking on the DIV causes the image inside to change state. However, clicking on the same DIV again doesn't return the image to its original state; it remains stuck in the ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Tips for effectively redirecting traffic to another website

Is there a way to redirect someone from a page URL like example.com/2458/233 to example2.com/2458/233? The first URL contains only a file that redirects to the other domain. Can anybody provide instructions on how to achieve this process? To clarify furt ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

Angular JS - Establishing a Connection to Woocommerce OAuth v1

I'm having trouble authenticating myself with the rest service. I attempted to use this library to generate all the necessary parameters as mentioned here, and I constructed the request like this: $scope.oauth = new OAuth({ consumer: { p ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

Issues with returning undefined values in JSON with Node.js and AngularJS

I have developed an application that communicates with an API to retrieve and display data. The process involves entering a username in the client input, which is then sent to the server. Upon checking, everything seems to be working fine at this stage. H ...

Printing the selected value from a drop-down box in HTML with JavaScript

I'm in the process of creating a web page structured like this: <html> <head> <title>Bug UI</title> </head> <body> <script> function myfunc() { //what should I include here?? } </script> <form> ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...