简体   繁体   中英

Vue: How do I generate a new instance of a div with a buttonclick?

I need to create a function that generates a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked. The button should be the only thing visible on the webpage before that. How do I do?

I know that it may be possible to do this with document.appendChild. Is there a better way?

I am using toggle-function that works great, I have included it in the code to give you the whole picture.

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>

So what you can do is set a number in data for the number of <div> elements and use v-for with a range . For example

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

And in your template

<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>

and in your methods...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM