Guide on integrating dynamic component addition and event listening with JavaScript in Vue3

Lately, I've been diving into Vue3 and exploring how to dynamically add components while allowing the parent component to listen for events from the child components. To illustrate my goal, I have crafted the code snippet below. Essentially, I am looking to append a new button when hovering over any existing button. However, as observed, only the first button triggers the hello function, indicating that the line 7 code "v-on:addButton: hello" in App.vue is not functioning as intended. I am seeking guidance on how to adjust the code to achieve my desired outcome or if there is a simpler approach to implement this feature.

Child component Hello.vue

<script setup lang="ts">
  defineProps(['text'])
  defineEmits(['addButton'])
</script>

<template>
  <button @mouseenter="$emit('addButton')">{{text}}</button>
</template>

Parent component App.vue

<script setup>
  import {createApp} from 'vue'
  import Hello from './components/Hello.vue'
    
  let cnt = 0
  function hello() {
    console.log('you enter a button')
    const app = createApp(Hello, {"text": String(cnt++), onaddButton: hello})
    const newNode = document.createElement('div')
    document.getElementById("rootDiv").append(newNode)
    app.mount(newNode)
  }
</script>

<template>
  <div id="rootDiv">
    <Hello text="0" v-on:addButton="hello"/>
  </div>

Update:

Thank you for the responses. I discovered that a simple modification from "v-on:addButton: hello" to "onaddButton: hello" resolves the issue.

Answer №1

Working directly with the DOM in Vue can cause reactivity and binding issues. Instead, a better approach is to utilize the cnt variable along with the v-for directive for rendering components:


<script setup>
  import {ref} from 'vue'
  import Hello from './components/Hello.vue'
  
  let cnt = ref(0)
  function addBtn() {
     cnt.value++
  }
</script>

<template>
  <div id="rootDiv">
    <Hello v-for="i in cnt" :text="i" v-on:addButton="addBtn"/>
  </div>
</template>

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

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Ionic app encounters issue fetching local JSON data

I have been working on my Ionic application and I encountered an issue when trying to load local JSON data into it. I set up a http.get in my javascript to retrieve the data, but for some reason it's not showing up in the application. It seems like th ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

After the decimal point, there are two digits

My input field is disabled, where the result should be displayed as a product of "Quantity" and "Price" columns ("Quantity" * "Price" = "Total"). However, I am facing an issue where the result often displays more than 2 digits (for example: 3 * 2.93), desp ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

Building a follow/unfollow system in Node.jsLet's create a

I am relatively new to programming and I'm looking to implement a follow/unfollow feature in my application. router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{ user.findById(req.params.id) .then((otherUser)=>{ if(otherU ...

Parsing JSON data received from Angular using JSP

As I navigate through my Angular application, I'm encountering a challenge when trying to save data on the server side using JSP. The issue arises when Angular's $save method sends the object data in a JSON format that is not familiar to me. This ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

Can someone explain what {...props} means within the context of React Navigation's Stack.Screen?

Can you explain the importance of using {...props} on this specific page? <Stack.Screen name="Home"> {props => <HomeScreen {...props} extraData={someData} />} </Stack.Screen> Interestingly, my application functions correctly even w ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...

Leveraging jQuery to detect an AJAX load that does not involve the use of jQuery's AJAX method

Hi all, I have a challenging issue that I'm struggling with in terms of jQuery/JavaScript. I am fetching data through standard AJAX without using any frameworks like jQuery. Now, the dilemma is that once the page has loaded, I need to implement a jQu ...

Retrieve the text content of a span element using jQuery

How can I use jQuery to extract the text "cnn.com" from the given HTML structure? var txt = $(".example1 >.myNewTest").closest('.subexample2').find('span').text(); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3 ...

When the page is resized for mobile, the Bootstrap modal shifts downwards

I am encountering an issue with a modal that pops up on my webpage when clicked. It is perfectly centered in a browser view and smaller views. However, when I resize the page for phones, the modal shifts down the page and requires scrolling to see it. How ...

What steps can I take to display a "Sign in with Paypal" button on a React App?

Disclaimer: I am relatively new to React and have only been dabbling with it for a day. I came across this tutorial source code that is designed for logging in with Google. https://github.com/The-Tech-Tutor/spring-react-login My goal is to integrate a "L ...

Identifying the active input using React hooks

Currently exploring React Hooks and trying to determine which input is currently in focus. I have a collection of inputs that are generated dynamically, and I would like to identify the selected one so that I can append a value to it upon button click. ...

What is the best way to send an array of numbers by utilizing e.target.value and React useState Hooks?

Trying to update the numbers array by passing it into submitNumbers() and using an onChange event. Issue arises when trying to use useState() to handle the array. When attempting to log these constants while the code is running, they are returning as not ...

Is there a way to update a JSON key using the "onchange" function in React?

I'm facing an issue. I have a form with two inputs. The first input is for the key and the second input is for the value. I need to update the values in the states whenever there is a change in the input fields, but I'm unsure of how to accomplis ...

Creating a connection between my .html and .ejs files: A step-by-step guide

I have successfully created a pair of HTML files - index.html & contact.html. Within these files, I have implemented a navigation bar that allows for seamless transition between them. Recently, I delved into the realm of retrieving APIs and crafted an app ...

The functionality of ng-switch appears to be malfunctioning

Take a look at this code snippet: <script src="angular.min.js"></script> <script src="jquery-1.6.4.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller("myContr ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...