When attempting to modify the state in a parent component from a child using the composition API in Vue 3, the error "this.$emit() is not a

//Main component

<template>
   <childComponent @onChangeData='updateData' />
</template>
<script>
   setup() {
   const state = reactive({
     data: 'example'
   });
    
   function updateData(newValue){
     state.data = newValue
   }
   return { updateData}
},
</script>

//Child Component

<template>
 <button @click='triggerChange("world")' />
</template>

<script>
   setup() {

   function triggerChange(input){
     this.$emit('onChangeData', input)
   }
   return{triggerChange}
},
</script>

I am facing difficulty in updating the parent's reactive state from a button click event in the child component. An error message "this.$emit is not a function" keeps showing up. I have tried various alternatives such as using @onChangeData='updateData()' instead of @onChangeData='updateData', utilizing arrow functions, and more, but to no avail. The provided code snippet reflects my situation succinctly. Hopefully, my issue is clear now.

Answer №1

Check out the code snippet below, this is not structured the same way in the composition API compared to the options API. In order to make it work, you need to utilize the emit function passed to the setup function:

const { reactive } = Vue
const app = Vue.createApp({
  setup() {
    const state = reactive({
      data: 'anything'
    });
    function changeData(v){
       state.data = v
    }
    return { changeData, state }
  },
})
app.component("ChildComp", {
  template: `
    <div>
     <button @click="change('hello')">click</button>
    </div>
  `,
  setup(props, {emit}) {
    function change(v){
      emit('onchangeData', v)
    }
    return { change }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
   <child-comp @onchange-data='changeData'></child-comp>
   <p>{{ state.data }}</p>
</div>

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

Tips for changing input field type from "password" to "text" in Angular?

Is there a way to dynamically convert an input field with type="password" to type="text" in Angular? In my demo, I have two input fields labeled Mobile no and Re-enter mobile number. I want these fields to change to type="text" if the user inputs the same ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

How can Nuxt effectively manage Login and Logout buttons to prevent content flashing?

As a newcomer to Nuxt, I've successfully implemented a bootstrap header with the standard v-if="authenticated" logic for displaying login/logout buttons. The authentication provider I'm using is Firebase, which includes an onAuthStateChanged met ...

The scroll function is executed only one time

I'm currently working on implementing a sticky sidebar snippet using jQuery. However, I am facing an issue where the function within .scroll() is only executing once instead of on every scroll event. Can anyone help me identify what I might be doing i ...

Switch up image origin when image reaches screen boundary

I am trying to create a DVD screensaver with changing images each time it hits the edge, but I can't seem to get it to work. I've attempted using the code snippet below: var img = document.getElementById("myImage"); img.src = 'img/new-image. ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

Tips for inserting a new entry into the KendoUI DataSource module

I have set up a KendoUI DataSource on my webpage that retrieves data in JSON format from a method. Here is the script I am using: <script id="template" type="text/x-kendo-template"> <tr> <td>#= ID #</td> ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

Is it possible to simultaneously send a JSON object and render a template using NodeJS and AngularJS?

I'm currently facing issues with my API setup using NodeJS, ExpressJS Routing, and AngularJS. My goal is to render a template (ejs) while also sending a JSON object simultaneously. In the index.js file within my routes folder, I have the following s ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Transferring data from a table to another window

Currently, I am retrieving values from a database and displaying them in a table. I would like to add a button to each row that will allow users to view more details about that specific row. At the moment, only ThesisID, AuthorID, and Title are visible. ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

Encountering a syntax error with JSON.parse() when using MVC 4 Razor with Jquery Ajax

I am encountering an issue with my MVC 4 application login page. I am attempting to utilize a jQuery ajax request to my login controller to check if the user exists. Here is the snippet of my jQuery code: $(document).ready(function () { $("#btnSub ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

The error message thrown is: "TypeError - attempting to call an undefined function

I'm new to working with node and express, and I encountered an error when running my App. Does anyone have any solutions? I suspect the error may be in this line "app.use(express.static(user));" but I'm not certain. var express = require('e ...

What is the best way to add CSS files to .vue components?

I am utilizing the official vue-cli scaffolder and attempting to incorporate normalize.css into App.vue using the following method: <style scoped> @import "/node_modules/normalize.css/normalize.css"; .app { font-family: Helvetica, Arial, san ...

Is there a way to determine when an HTML video has finished playing?

I'm working on a webpage that features multiple videos. I want to capture a specific value from an input field and display it once a video finishes playing. Below is my current setup: HTML <input type='text' name='profileUsernam ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...