Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript.

Similar to how you would add a new modal in jQuery with

$("body").append("<div class='modal'></div>")

For example: https://jsfiddle.net/yu9oca2n/

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

JQuery

Sample JQuery code:

$("#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

Parent Component:

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

Answer №1

Implement an array within the component data and display a modal for each item in the array

<template>
  <div>
    <p>Greetings</p>
    <hr>
    <a @click="addModal">Add Modal</a>
    <hr>
    <modal v-for="number in modals" :num="number" :key="number" @clickEvent="handleClick($event, number)"></modal>

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

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

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

Utilizing Node Mailer and Sendgrid to send emails in an Angular MEAN stack project with the angular-fullstack framework generated by Yeoman

Trying to figure out the best location for the code responsible for sending an email through a contact form in my Angular App using angular-fullstack MEAN stack from Yeoman. I managed to implement the email sending logic in the app.js file on the server s ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Triggering JavaScript events using jQuery

I am experiencing an issue with an input element that triggers a modal containing a table when clicked. From this table, you can select a line and a JavaScript function modifies the value of the input element accordingly. However, I am trying to detect the ...

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Cross-domain scripting with JavaScript

I currently manage 2 subdomains securityservices.example.com workstations.example.com All workstations are associated with the workstations.example.com One of the workstations, known as WS789012 on the domain, is fully qualified as: WS789012.workst ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

updateProfile: async function(req, res) { try { const update = req.body; const id = req.params.id; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.&a ...

What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself? I've attempted it like this but seem to be making a mistake somewhere. ...

Using React to create multiple modals and dynamically passing props

Each item in my list (ProjectActivityList) has an Edit button which, when clicked, should open a modal for editing that specific item. The modal requires an ID to identify the item being edited. var ProjectActivities = React.createClass({ onEditItem: ...

window.onresize = function() { // code here

Here's an example of code I've been working on: $(document).ready(function (e) { adjustSize(); $(window).resize(adjustSize); function adjustSize() { var windowWidth = parseInt($(window).width()); if (windowWidth > ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

What is the best way to incorporate a search feature within Bootstrap cards?

I've been struggling to incorporate a search feature within my bootstrap cards. Despite trying various online methods, none have proven successful for me so far. Below is my HTML code - any assistance in implementing a search filter into my app would ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Exceeded call stack size error when using Vuex and Onboard.js

Currently, I'm facing an issue while attempting to utilize Vuex and Onboard.js for storing a web3 provider in my DApp. Each time I try to commit the selected wallet in my state, I encounter a Maximum call stack size exceeded. Below is how my files are ...