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

Sending data from a JSP page to a JavaScript function

I am working on a script that dynamically adds text boxes based on a specific time interval. <script type="text/javascript> $(document).ready(function() { var data = $('#data').val(); var counter = 1; var d = new Date(); va ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Determine the status of caps lock with a single click of a button

I am working on an application that includes a textbox and a button. I need the application to indicate whether the Caps Lock key is activated or deactivated when a user types text in the textbox and clicks the button. ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

What exactly does the term "library" refer to in the context of jQuery, a JavaScript

I'm confused about the concept of a library - when it comes to jQuery, can it be described as a large file containing multiple plugins that are pre-made and ready for use? ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...

``What is the mechanism behind callbacks in AngularJS when making a call to a REST service?

Currently, I am diving into the world of AngularJS and REST. The code snippet that I'm analyzing has the term callback repeatedly used in an authentication function. I'm curious to know if "callback" is a JavaScript or Angular keyword, or simply ...

What is the process for obtaining all of the options from a jQuery datepicker in order to create a new datepicker with identical settings?

Is there a way to easily replicate all options of a jQuery datepicker when creating a new instance? I am trying to duplicate a table that includes 2 datepickers with different settings. For reference, you can view an example here: http://jsfiddle.net/qwZ5 ...

Utilizing numerous await statements within a single asynchronous function

My async function has 3 awaits, like this: const sequenceOfCalls = async(req, res, next) =>{ await mongoQuery(); await apiCall1(); await apiCall2(); } apiCall1 uses response of mongoQuery and apiCall2 uses response of apiCall1. The issue is ...

Incorporate personalized buttons into the header navigation for each view using VueJS

In my VueJS project, I attempted to include custom buttons in the sub navigation menu which could be customized for each view. Initially, I tried adding a simple property to the main data element, but that didn't yield the desired results. Then, I cam ...

Tips for creating a sticky bootstrap column that remains in place as you scroll

I am looking to design a FAQ page similar to Twitter's FAQ. The goal is to have the left column remain fixed in its position while allowing users to scroll through the content. Here is what I have attempted so far, but it is not functioning as expect ...

What is the best way to eliminate a single layer of component prefix in a Nuxt application?

Folder structure: components components/sections/ components/sections/profile components/sections/profile/Sidebar.vue components/sections/main/InformationSlider.vue This is the default path prefix for these components without any configuration: <Secti ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Verify if the header value corresponds

How can I validate the header value in a Node.js application? I want to restrict access to a certain route only if the user includes a specific header and its value matches what is expected. For instance, let's say the route requires a header like Acc ...

I'm having trouble with my Discord app command. Every time I try to use it, I keep getting the error messages "The application did not respond" and "Dispatching MESSAGE_SEND_FAILED." How

Having a good amount of experience in JavaScript, I was optimistic about developing a Discord application as it seemed quite manageable. Eventually, I successfully integrated the bot into a server and implemented a command that is now listed in Discord&apo ...

Is it possible to run two commands in npm scripts when the first command initiates a server?

When running npm scripts, I encountered an issue where the first command successfully starts a node server but prevents the execution of the second command. How can I ensure that both commands are executed successfully? package.json "scripts": { "dev ...

Tips for concealing JavaScript code while inspecting elements with AngularJS

Is it possible to display minified JavaScript code when using Angular and inspecting elements? ...

Generating unique ObjectIDs for each object is crucial before saving documents in Mongoose

I need to generate a unique ObjectID for every object within my array. The challenge is that I am fetching products from another server using a .forEach statement and adding them to my array without a Schema that automatically creates an ObjectID.... Prod ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...

I successfully linked expressjs, nodejs, reactjs, and mysql in my project. I'm puzzled as to why everything runs smoothly after I restart my express server, but encounters issues when I refresh the page

express path users.js var express = require('express'); var router = express.Router(); const connection = require('./MySQL.js') /* Accessing user data. */ router.get('/', function(req, res, next) { connection.connect() ...