1
votes

I have a doubt on how to create dynamic components, and not by the label <component :is=''>, if not, this component does not exist in the DOM, and through javascript insert it.

As in jquery add a $("body").append("<div class="modal"></div>"), to add a new modal

Example: https://jsfiddle.net/yu9oca2n/

Code: https://codesandbox.io/embed/vue-template-5cx5l?fontsize=14

JQuery

code example JQuery

$("#button").click(function() {
  $("#modals").append("<div class='modal'>modal</div>");
});
<!doctype html>
<html>

<head></head>

<body>
  <div id="modals"></div>
  <hr>
  <button id="button">add input tag</button>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</body>

</html>

VUE

Componet Parent

<template>
  <div>
    <p>Hello</p>
    <hr>
    <a @click="insertModal">Insert Modal</a>
    <hr>

    <modal num="1"></modal>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  methods: {
    insertModal() {
      /**
       * How to do so that when you enter here,
       * add one more modal, without putting this in a list,
       * because this modal can be called from anywhere on the web
       *
       * MODAL : <modal num="_x_" @clickEvent="eventClick"></modal>
       */
      // ??
    }
  },
  eventClick() {
    /** modal event click */
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Component modal

<template>
  <div>MODAL {{num}}</div>
</template>

<script>
export default {
  name: "modal",
  props: ["num"],

  data: function() {
    return {};
  },

  methods: {}
};
</script>
1

1 Answers

0
votes

Create an array in component data and show a modal per every item in array

<template>
  <div>
    <p>Hello</p>
    <hr>
    <a @click="insertModal">Insert Modal</a>
    <hr>
    <modal v-for="num in modals" :num="num" :key="num" @clickEvent="eventClick($event, num)"></modal>

    <modal num="1"></modal>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  data() {
     return {
       modals: [],
     };
  },
  methods: {
    insertModal() {
      this.modals.push(this.modals.length)
    }
  },
  eventClick($event, modalNumber) {
    /** modal event click */
  }
};
</script>