Vue.js not firing onclick event

Here is a code snippet for a Vue.js template:

<script type="text/x-template" id="ti-page-inquire">
    <div>
        <h3 class="mdc-typography--headline3">{{page.name}}</h3>
        <ti-button v-bind:button="page.button" v-on:click="onSubmit"></ti-button>
    </div>
</script>

<script type="text/x-template" id="ti-button">
    <button class="mdc-button mdc-button--raised" v-bind:title="button.name">{{button.name}}</button>
</script>

script

    Vue.component('ti-page-inquire', { 
        props: ['page'],
        template: '#ti-page-inquire',
        methods : {
            onSubmit : function() {
                alert(1);             
            }
        }
    });

    Vue.component('ti-button', {
        props: ['button'],
        template: '#ti-button',
        mounted: function () {
            // ripple on button
            mdc.ripple.MDCRipple.attachTo(this.$el);
        }
    });

Upon clicking the custom button, no action seems to be triggered. It appears that the issue lies in locating the onSubmit function within the ti-button component rather than the ti-page-inquire component. How can I direct it to search within the correct component?

Answer №1

When it comes to components, think of them as 'black boxes' where you capture all events and then broadcast them to the outer world.

Check out this Fiddle example for reference

Vue.component('ti-button', {
    props: ['button'],
    template: '#ti-button',
    mounted: function () {
        // Add ripple effect to button
        mdc.ripple.MDCRipple.attachTo(this.$el);
    },
    methods: {
      buttonClicked: function() {
        // Emit event when button is clicked
        this.$emit('button-clicked');
      }
    }
});


<script type="text/x-template" id="ti-page-inquire">
    <div>
        <h3 class="mdc-typography--headline3">{{page.name}}</h3>
        <ti-button v-bind:button="page.button" v-on:button-clicked="onSubmit"></ti-button>
    </div>
</script>

<script type="text/x-template" id="ti-button">
    <button class="mdc-button mdc-button--raised" v-bind:title="button.name" @clicked="buttonClicked">{{button.name}}</button>
</script>

Answer №2

The reason for this issue could be that you are required to listen for a native click event. In order to achieve this, you must utilize the .native modifier.

<ti-button v-bind:button="page.button" v-on:click.native="onSubmit"></ti-button>

This method will only function correctly if the button serves as the root element within your ti-button component. Alternatively, if the button is not the root element, you will need to pass your event listeners to the button within the ti-button component like so:

<button v-on="$listeners" ...> ... </button>

Answer №3

One way to send an event from the child component ti-button to its parent is by using the this.$emit function :

Vue.component('ti-button', {
  props: ['name'],
  template: '#vButton',

  data: {
    name: 'hi'
  },
  methods: {
    submit() {
      this.$emit('submit')
    }
  }
});
<template id="vButton">
    <button v-bind:title="name" @click="submit">{{name}}</button>
</template>

The emitted event submit can then be listened for in the parent component with v-on:submit="onSubmit" and handled using the onSubmit method:

<script type="text/x-template" id="ti-page-inquire">
  <div>
    <h3 class="mdc-typography--headline3">{{page.name}}</h3>
    <ti-button v-bind:button="page.button" v-on:submit="onSubmit"></ti-button>
  </div>
</script>

Vue.component('ti-page-inquire', { 
   props: ['page'],
   template: '#ti-page-inquire',
    methods : {
        onSubmit : function() {
            alert(1);             
        }
    }
});

If you need to pass parameters along with the event, you can do so like this :

this.$emit('submit',params)

The variable params can contain any type of data.

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

Animating the dimensions of objects in THREEjs

In my project using THREE.js, I am aiming to create a captivating animation where an object gradually shrinks into nothingness. After exploring solutions on Three.js - Animate object size, I found methods to adjust the size of an object. However, the chan ...

Sort by the date using a specific data attribute

My main objective is to showcase a multitude of posts on this website, sourced from a server that does not organize them by date. I, however, wish to arrange them based on their dates. Currently, the layout on my website looks something like this: < ...

Minifying Angular using grunt leads to 'Error initializing module' issue

Currently, I have multiple controllers, models, and services set up as individual files for preparation before minification. My goal is to combine and minify all these files into one JS file for production. To illustrate how my files are structured, here ...

What is the process for uploading an image and entering text into the same row in Google Sheets?

Hello, I am currently working on a Google Script web app that enables users to upload 10 photos along with comments for each photo. This information will then be inserted into a Google Sheet when the user clicks the 'upload' button on the web app ...

By utilizing geocoordinates, arrange items in order of proximity to the individual's current location

Looking to organize an array based on the user's location in an AngularJS/ionic app. Specifically, the goal is to rank restaurants that are closest to the current user location 1/ Within my controller.js, I have the following code to retrieve the use ...

Vue.js is throwing an error because it cannot find the property or method "blah" when referencing it during rendering

Can you explain why Vue 2 throws an error indicating that a prop is not defined, even though it is statically defined in the parent template? Note: This error does not occur when I include the JavaScript code within the .vue file's script tag instead ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Utilize another function located within a JavaScript module

I'm encountering an issue while trying to reference the getJSONS function from another function within the script. The error message I'm seeing is (node:5857) UnhandledPromiseRejectionWarning: TypeError: this.getJSONS is not a function. How can ...

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

The functionality of the Bootstrap carousel appears to be malfunctioning

My attempt at creating a carousel has hit a snag - it seems to be stuck on the first image and the next and previous buttons aren't functioning. I've gone over the code multiple times, but I just can't pinpoint the issue. Any assistance woul ...

The command "babel-node" is not recognized as either an internal or external command - Babel 7

I'm currently working with babel version 7.6.x and I have configured the setup as follows: In the package.json file: "scripts": { "dev": "nodemon --exec babel-node bin/index.js", "start": "babel-node bin/index.js", "test": "echo \" ...

Changing a password for a user account using Keycloak Identity Provider

In my Vue application secured by Keycloak using keycloak-js, I am working on implementing a feature where each user has an account page to change their password. However, I have encountered an issue as Keycloak does not seem to provide an endpoint to check ...

Guide to displaying a task within a table cell after a user submits the form

<?php $servername = "localhost"; $username = "u749668864_PandaHost"; $password = "Effy1234"; $dbname = "u749668864_PandaHost"; $q = $_REQUEST["task"]; $task = $q; echo $task; $conn->close(); ?> Exploring the world of ajax has left me scratching ...

Disappearing Image on Hover in JavaScript and HTML

I'm encountering an issue with my JavaScript hover effect on two images. When a user hovers over the arrow image, it should change to a hover version of that image. Additionally, if the user clicks on the arrow, it should trigger another JavaScript fu ...

How to specifically exclude a checkbox from the "select all" function in J

One way to select all checkboxes with HTML code: Select All <input type="checkbox" name='select_all' id='select_all' value='1'/> To achieve this with Javascript code: <script type="text/javascript> $(&apos ...

Converting a string representing time to a date object in Angular

Converting a string representation of time to a Date object var timeString = "09:56 AM"; this.audit_time = new Date(timeString); // Error: Invalid date I'm facing an issue with this conversion. Any suggestions on how to correct it? Please help me s ...

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

Creating custom shaders in three.js that can receive shadows involves a few key steps. Let

For more information, you can visit the original post here. The task at hand seems to be quite complex due to the lack of documentation and examples on this specific topic on the three.js website. Currently, I am able to render the correct image and, with ...

Having difficulty grasping the concept of using unicode characters with canvas fillText

I am attempting to showcase special characters in a font using the canvas fillText feature. The code I am employing is as follows: canvas = document.getElementById("mycanvas"); context = canvas.getContext("2d"); hexstring = "\u00A9"; //hexstring = " ...

Creating rows within a table in React.js using the map method: Techniques to follow

Here is my code snippet: const [tasks, setTasks] = useState(''); I am simulating data with a mock server. function fetchTasks() { axios.get('http://localhost:4000/tasks') .then(function (response) { ...