Guide on attaching event handlers to a standard button template using Vue JS

Just diving into Vue.js and I have a specific requirement.

I need to attach events to a generic button template.

I attempted to do so using the following approach.

    Vue.component('ac-btn', {
    props: [
        'clickevent'
    ],
    methods: {
        greet: function () {
            alert("I am Called");
        }
    },  
    template: '<button type="button" :click="clickevent" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});

Unfortunately, the click event is not being triggered. Any suggestions on how to dynamically bind a click event to a generic button template?

Edit:

@Saurabh

I followed your advice and here is the implementation in my project.

Vue.component('ac-parent', {
    methods: {
        greet: function () {
            alert("Hiey");
        }
    },
    template: `<div class="container-fluid">
    <div class="row">
        <div class="col-lg-3 col-md-4">
            <div>
                <ac-child :onClick="greet">Custom value to replace generic slot value</ac-child>
            </div>
        </div>
     </div>`
});

Vue.component('ac-child', {
 template: '<button type="button" @click="clickevent" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});

Even after this modification, the functionality is not working. Any insights on where I might be going wrong?

Answer №1

A more efficient approach is to avoid passing a callback through a component prop like this: :onClick="greet". Instead, it is recommended to emit an event from the child to the parent component using this.$emit('click', event). This way, you can handle the event in the parent component and perform the necessary actions. Subsequently, you can utilize the button component as if it were a native button by using

<ac-child @click="greet">Custom Button</ac-child>

Answer №2

Kindly attempt using the code provided below:

app.js

Vue.component('ac-parent', {
    methods: {
    greet: function () {
        alert("Hey");
    }
},
template: `<div class="container-fluid">
    <div class="row">
        <div class="col-lg-3 col-md-4">
            <div>
                <ac-child :onClick="greet">Custom value to replace generic slot value</ac-child>
            </div>
        </div>
    </div>
    </div>`
});

Vue.component('ac-child', {
    props: ['onClick'],   
    template: '<button type="button" @click="onClick" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});

new Vue({
    el: '#vue-app'
})

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Title</title>        
        <script src="https://unpkg.com/vue"></script>
    </head>
    <body>
        <div id="vue-app">
            <ac-parent></ac-parent>               
        </div>
    </body>
    <script src="./app.js"></script>
</html>

If you encounter any obstacles, please feel free to inform me

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

Creating secure RSA keys using a predetermined seed - a step-by-step guide

Is it possible to utilize a unique set of words as a seed in order to recover a lost private key, similar to how cryptocurrency wallets function? This method can be particularly beneficial for end-to-end encryption among clients, where keys are generated o ...

What are the potential drawbacks of relying heavily on socket.io for handling most requests versus using it primarily for pushing data to clients?

Is it advisable to switch AJAX routes (called with $.Ajax in jquery) like: GET /animals GET /animals/[id] POST /animals To socket.io events (event bound on client and server for client response): emit("animals:read") emit("animals:read", {id:asdasd}) ...

retrieve a subdocument from an array in MongoDB

In my MongoDB database, I have the following data structure: {doc: { array_doc:[....//many documents]} } Currently, I am working with Mongoskin in MongoDB 2.2 with Node.js 0.8. var code_doc='HSKD41814541211'; var db = mongo.db(perm+"@127.0 ...

Transforming Vue2 code into standalone web components

I'm attempting to convert the autocomplete search feature from this codepen into pure web components. Unfortunately, I've run into some issues with slots not working and other unidentified problems. Here's what I have so far: Search-select ...

Is there a workaround to prevent me from using overflow: scroll when I addEventListener("touchmove", preventBehavior, false)?

I am developing an iOS app using PhoneGap, and I have encountered a problem where the window cannot be moved due to the code document.addEventListener("touchmove", preventBehavior, false); Although this code prevents the window from moving, it also stops ...

Having difficulty inputting password for telnet login using Node.js

When I use telnet from the Windows command line, everything works smoothly: > telnet telehack.com (... wait until a '.' appears) . login username? example password? (examplepass) * * * * * * * Logged... (...) @ (This is the prompt when you ...

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

Unleashing the Power of Vuejs: Setting Values for Select Options

I have a specific requirement in my Vue application where I need to extract values from an XLS file and assign them to options within a select dropdown. Here is what I currently have: <tr v-for="header in fileHeaders" :key="header"&g ...

Ways to move information across components positioned in separate perspectives

In the same view, I have two components placed in close proximity. @extends('layouts.app') @section('content') <bus></bus> <bus2></bus2> @endsection Upon clicking a button, I aim to transfer data (name) from o ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...

"Twice the loading of Meteor templates: once with an undefined collection, and once with it

After searching various resources for solutions to my issue, I stumbled upon this helpful and . Both of these links provided valuable insights. The issue I'm facing is that one of my templates is loading twice - first with the collection undefined, ...

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...

Numerous inline notations in html code

I need help figuring out how to prevent a hyperlink from opening a new tab by commenting out the HTML code. <a href="<!--http://www.google.com=-->" target="_blank" onclick="javascript:alert('Navigation Prevented')">CLICK HERE FOR GOO ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

Create a new array of objects by extracting specific properties from an existing array of objects

Consider the input array below: const initialArray = [{name: 'john', age: 12, height: 178, likes: 'music'}, {name: 'mike', age: 22, height: 181, likes: 'sport'}, {name: &ap ...

jquery mobile popup message will fade away within a short time interval

In my main page, I have the following code: $(document).bind("pageinit", function () { $.mobile.loading('hide'); }); I am displaying a popup message using the following code: $.mobile.loading('show&apos ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

Error encountered while attempting to import the mongoose npm module into a React application

I'm encountering an issue in my React project where I am trying to include an npm module within a component. Here's an example: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', {useNewUrlParser ...