What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal? Just as a heads up, the button is generated using v-for in the child component.

Answer №1

Your child component could be structured as shown below:

<template>
  <div class="child">
    <button @click="buttonClick">Button</button>
  </div>
</template>

<script>
  export default {
    props: ['buttonId'],
    methods:{
      buttonClick() {
        this.$emit('buttonClick', this.buttonId)
      }
    }
  }
</script>

As for your parent component:

<template>
  <div class="parent">
    <child v-for="i in 5" :buttonId="i"></child>
  </div>
</template>

<script>
  import Child from './Child.vue'

  export default {
    components: {
      Child,
    },
    methods: {
      onButtonClick(buttonId) {
        console.log('Received a click event from button ', buttonId)
      }
    },
    mounted() {
      this.$children.forEach(child => {
        child.buttonClick()
      })
    }
  }
</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

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

Guide on extracting data from MongoDB using VueJs

After successfully retrieving data from MongoDB using NodeJS, I am encountering an issue where the fields inside each object in the array are empty when trying to display them on my HTML page. The data is being fetched and displayed correctly in Chrome, bu ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...

How to Prevent Scrolling When Modal is in Use on Full Page JS

I am trying to achieve the functionality where when the modal is open, I want to prevent full-page scrolling in JavaScript. The issue arises when I open the modal and try to scroll, it ends up moving the content that's behind the modal, which is actua ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

Generating a text document with the power of Vue.js

Currently, I am encountering some challenges in implementing an "export" feature for my application. The reason behind wanting to add this functionality is simple: Once users have completed certain calculations within the application, they may wish to save ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Inject the JSON data fetched through AJAX into Datatables

I have been successfully using the datatables plugin to populate multiple tables with data. However, I realized that instead of making separate AJAX calls for each table, I could optimize by fetching the data once and storing it in a variable to be used by ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

What is the method for displaying a div adjacent to a password input field?

I am attempting to display a password verification box next to an input field. The current logic is functioning properly, but the box containing all password requirements is not appearing in the correct position. Instead of being positioned adjacent to the ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

Setting up VueJS with Nginx and Docker resulted in a local ERR_EMPTY_RESPONSE error

I'm new to using Docker, so please bear with me as I try to figure things out. My current challenge is dockerizing my Vue application with Nginx and a development container. However, neither seems to be working for me at the moment. I've been f ...

How can I extract a standalone CSS file from a single SCSS file using VueCLI and Webpack?

Currently, I am working on an app using VueCLI and webpack. The main.js file contains all the vue components and scss assets which compile into global .js and .css files as expected. In addition to this setup, there is a requirement for a single example.s ...