Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes:

<div class="token-checkboxes">
  <span class="checkbox-span" v-for="token_obj in token_to_vue_obj">
    <input v-on:change="plot()" type="checkbox" id="checkbox" v-model="token_obj.show">
    <label for="checkbox">{{ token_obj.token }}</label>
  </span>
</div>

Is there a simple way to "forward" an event on a parent element to a child or vice versa? Let me know!

Answer №1

If you want to update the model value when clicking on the outer pill element, you can add an event listener for it. This may not directly forward the event, but it will achieve the same result by toggling the checkbox.

<span class="checkbox-span"
      v-for="token_obj in token_to_vue_obj"
      v-on:click="token_obj.show = !token_obj.show; plot()">

Edit (check comments): It is recommended to remove plot() from the change handler of the <input> element to avoid calling the function twice when clicking the checkbox.

Take a look at the code snippet below.

var app = new Vue({
  el: '.token-checkboxes',
  methods: {
    plot() {
      console.log('Plot called!');
    }
  },
  data: {
    token_to_vue_obj: [
      { token: '_#misc',  show: true },
      { token: '_#study', show: true },
      { token: '_#code',  show: true },
      { token: '_#debug', show: true },
      { token: '_data',   show: false }
    ]
  }
})
.checkbox-span {
  background-color: lightgrey;
  padding: 0.5em;
  border-radius: 0.5em;
  border: 2px solid black;
  margin: 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div class="token-checkboxes">
  <span class="checkbox-span"
        v-for="token_obj in token_to_vue_obj"
        v-on:click="token_obj.show = !token_obj.show;plot()"
        v-bind:key="token_obj.token">
    <input type="checkbox" class="checkbox" v-model="token_obj.show">
    <label for="checkbox">{{ token_obj.token }}</label>
  </span>
</div>


Edit: Make sure to address the issue mentioned in the comment below regarding the non-unique id="checkbox".

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

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

Create a unique component in ReactJS with the react-google-maps package to enhance your user interface

I would like to integrate a custom marker component into the map, but I have observed that using react-google-maps/api does not support rendering custom components. To illustrate this, here is an example of the code I used: const CustomMarker = ({ text }) ...

Effective Angular - ensuring all API calls are completed in a forEach loop before returning the final array

Struggling with the asynchronous nature of Angular, I'm faced with a challenge. My task involves looping through various cards where certain types require API calls while others do not. However, upon completion of the loop, only the cards that do not ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...

Script for uploading multiple images without using flash, with customization options available for each individual upload

Looking for a non-flash images uploader script that has the following features: Ability to upload multiple files Supports drag and drop functionality Displays progress bar for each upload Shows small preview of each upload Allows for resumable downloads ...

I am looking to dynamically load a script only after retrieving specific data from a JSON file in Next.js

I am trying to ensure that the Script tag loads after the data.post.content is loaded within the HTML. Specifically, my goal is to execute the MathJax.js script inside the HTML. This is the code I have: return ( <div> <h1>{data.post ...

JavaScript is having trouble locating the HTML select element

Having trouble selecting the HTML select element with JavaScript? You're not alone. Despite trying different solutions found online, like waiting for the window to fully load: window.onload = function(){ var opt = document.getElementsByName("prod ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

Increase the date by one day excluding weekends (Saturday and Sunday)

My current code is designed to add +1 day to the current date. var date = '30 Apr 2010'; var actual_date = new Date(date); var final_date = new Date(actual_date.getFullYear(), actual_date.getMonth(), actual_date.getDate()+1); Now, I am looking ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

Optimizing mapActions for nuxt.js: Best practices

When working with a nuxt.js store, I encountered an issue while trying to use mapActions. The problem arises when using the 'dispatch' method everything functions properly, but as soon as I switch to mapActions, I start receiving a 'Maximum ...

submit the contact form information to both the database and email for further processing and storage

Currently, I have the code for connecting to a database and mail.php. I am able to save contact form data in the database successfully, but I also want to send an email to my address which I'm unsure how to do with manage_comments.php. Here are the ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

Exploring the capabilities of Set() and the for..in loop in JavaScript

function removeDuplicates(menuArray) { let flatmenus = menuArray.flat();//This method combines child and parent arrays into one unique array let combinedMenu = new Set();//Creates an object that removes duplicate elements flatmenus.forEach(dish => ...

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

Error: The function loadJSON has not been declared

Currently utilizing the Atom text editor, I have successfully installed node.js along with npm install -g json. The installation process was smooth and the version information displayed correctly in the command prompt window. Running a server using nodemon ...

Adjusting the value of 'this' within a service using a function

I am a newcomer to Angular and currently delving deeper into its intricacies. Despite my efforts in researching, I have not come across a solution for the issue at hand. My service sets the initial value of this.totalCount = 0; Within my controller, upo ...

Apologies, but Discord.js is unable to access the property "user" of a null object

I am facing a perplexing issue that I cannot seem to wrap my head around. The function works perfectly on one server but fails on another. Below is the snippet of code in question: const user = message.author; let servericon = message.guild.iconURL; let se ...

Sharing environment variables in gulpfile with other JavaScript files outside NODE_ENV

Is it possible to pass a variable other than NODE_ENV from the gulpfile.js to another javascript file? gulpfile.js // Not related to NODE_ENV! let isDevelopment = true; somejsfile.js /* I need to access "isDevelopment" from the gulpfile.js... For the ...