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:

https://i.sstatic.net/hspnF.png

<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

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

Ways to separate a portion of the information from an AJAX Success response

I am currently working on a PHP code snippet that retrieves data from a database as follows: <?php include './database_connect.php'; $ppid=$_POST['selectPatientID']; $query="SELECT * FROM patient WHERE p_Id='$ppid'"; $r ...

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...

Utilizing Sequelize validation through condition objects

const db = require("../models"); const Meet = db.meet; checkDuplicateTime = (req, res, next) => { Meet.findAll({ where: { tanggal: req.body.date, waktu: req.body.time } }).then(time => { ...

Axios displays a status code of 0 instead of the expected 403

Trying to monitor the responses of requests using axios response interceptors has been quite a challenge for me. In one specific request that necessitates authorization, everything goes smoothly when the token is valid, and data is returned without any is ...

What could be the reason for the malfunction of my callback function?

This particular function is executed with the command node server const express = require("express"); const app = express(); const fs = require("fs"); const connectDb = require("./config/db"); const __init__ = (local = false) => { fs.writeFile( ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Positioning Images at the Top of the Screen in React Native

I have two images that I would like to display side by side at the top of the screen. <View style={styles.container}> <View style={styles.topWrapper}> <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} /> ...

Printing an array from JavaScript to an EJS template: Tips and Tricks

I'm currently working on a database-driven website that focuses on searching through people's profiles. When attempting to display information from a database query, I am encountering the issue of receiving [object Object]. Below are snippets o ...

An overview on adding a new element to an array of objects in AngularJS

I have a feature on my website where users can create via points. Each user starts with one point, and if they want to add more, they can click "add" to insert a new object in the array with an empty value. The user then has the option to input a new value ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Ensuring Filesize Verification Prior to Upload on Internet Explorer Using Javascript

Can JavaScript be used to verify a file's size before it is uploaded to the server at the client side? This application is developed using EXTJS and Java and is limited to Internet Explorer 7 on Windows XP machines. ActiveX cannot be used. The workf ...

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...

Retrieve the list of device tokens for the APNS service

Is it possible to retrieve a list of all device tokens on which my app is installed through an APNS endpoint? I am aware of the feedback service that provides the status of devices to whom messages are sent, but I believe this is only after the message ...

ag grid - issue with icons not appearing correctly

<script> import {AgGridVue} from "ag-grid-vue"; import 'ag-grid-enterprise'; import 'ag-grid-community/dist/styles/ag-grid.scss'; import "ag-grid-community/dist/styles/ag-grid.css"; import "ag-grid-community/dist/styles/ag-theme-a ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

When attempting to pass Rgraph image data through a jQuery AJAX call, a 403 Forbidden error is being

I have been working on a project that involves creating graphs/charts using the Rgraph PHP library. To generate these charts, my script follows these steps: Calculate the graph points and render the graph using the Rgraph Draw() method. Create an image d ...

The React/Redux application is experiencing difficulties with API calls, as they are returning empty responses and the actions are not being triggered

Hey there, I'm currently working on a React Native app and running into some issues with making API get requests. It seems like the response is throwing an error and the action isn't executing properly. I'll share my code below, so if anyone ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Conceal Reveal Secret Script

Can you help me with a question regarding the spoiler on this specific page? Here is the link: When I click on Windows, a table appears. However, when I click on Linux, the content of Windows disappears. I am looking to create a spoiler like this, but whe ...