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

Vue in d3 - the property ownerDocument is not defined

I'm currently working on integrating d3 charts with Vue. I've noticed that using a ref seems to trigger an error, but is that the correct approach? <template> <div ref="chart"></div> </template> const char ...

Vue.js failing to trigger code upon received message from socket.io server

I have been working on enabling communication between a Vue.js app and a remote, standalone socket.io server. I have successfully set up the Vue.js app to send messages to the socket.io server (confirmed through console logs on the Node.js instance). Altho ...

Device sending incorrect JSON format

A JSON response from a device is as follows: { "Order": ""3"", "ID": ""SHEET"", "Name": ""Time Sheet"", "ConID": ""!s?d2SzxcSDW1cf$*@4812sC#"" } The property values in the JSON are enclosed in double quotes, causing them to be incorrect. Is ...

Iterate through an array index within a map function in a ReactJS component

I am working with a map that contains images of metros, and I need to increment the number by 1 at each loop iteration. For example, the first loop will display {metrosImages[0]}, then {metrosImages[1]}, and so on until the loop reaches its end. The code ...

Guide on hiding a div element when clicked outside of it?

How can I create a dropdown feature in Khan Academy where it disappears when clicked outside but stays visible when clicked inside, using JavaScript/CSS/HTML? The current implementation closes the dropdown even on internal clicks. The code includes an even ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...

Ways to access information from doc.data()

<template> <div> {{ id }} {{ title }} </div> </template> <script> import { useRoute } from 'vue-router' import 'firebase/firebase-firestore' import { db } from '@/fdb' export default ...

How to avoid console messages when dealing with Axios 422 error handling?

When developing my application, I decided to use Laravel for the backend and Vue for the frontend. To handle validation errors, I chose to implement code 422 based on recommendations from this article. The PHP code snippet in my RegisterController: if ($t ...

Scrolling presentation with dynamic animations

Does anyone have any suggestions for creating a scrolling effect similar to the one on this website? I want to implement a scroll effect where each presentation page is revealed one by one when the user scrolls using their mouse wheel, encouraging them to ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Tips for updating the data value of a specific block using Vue.js

I am looking to develop a basic Vue.js application. Within this app, I have multiple counter blocks that are rendered using the v-for directive. In my data object, I initialize a 'counter: 0' instance. My goal is to increment and decrement only o ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Styling your Vuetify V-data-table with CSS

Struggling to add extra spacing between table rows, despite inspecting the page and verifying that my styles are not being overridden. Have read other Vuetify posts on applying CSS but still no luck. Any suggestions for why I can't style my table as d ...

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

How come my customized directive is not taking precedence over the original methods in AngularJS?

Following the guidelines in the Angular Decorator manual (https://docs.angularjs.org/guide/decorators), I attempted to create a directive and apply decoration to it. The directive's purpose is to display the current date and time. I included a (point ...

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...