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

Leveraging Node.js alongside a Spring backend

As I delve into a project involving React on the frontend and Spring on the backend (both running on the same machine), an interesting question arises. Given that Spring backend operates independently of Node, and the web browser is used to showcase the Re ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Managing the state in NextJS applications

I've scoured the depths of the internet in search of a solution for this issue, but unfortunately I have yet to come across one that effectively resolves it. I've experimented with various state management tools including: useContext Redux Zusta ...

Tips for Holding Off on Assigning Variables in Vue3 Component Until Pinia Store Data is Ready

I am currently developing a Vue.js application with Pinia for state management. In my component, I need to assign variables based on data retrieved from a Pinia store. However, I am facing an issue where the component assigns variables before the store dat ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

There seems to be an issue with the reactivity in the Vue Composition API

Currently utilizing Vue2, Vuetify, and the Vue Composition API (@vue/composition-api). Encountering an issue with the reactivity of the composition API. Let's delve into some code snippets: ---- companies.vue ---- <template> ... <v-data ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

Unable to display the retrieved list data using v-for loop from axios get request

I recently started using Vue.js and decided to create a simple HTML website with Vue.js to display data from myphpadmin using axios. Everything was working smoothly until I encountered an issue where I couldn't display the JSON message on my screen. n ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

Some design elements are present in the interface. The functionality of the data tables is working properly, however, upon reloading the page, the table header shrinks. Interestingly

[![enter image description here][1]][1] This is the JavaScript code along with my footer and header references. The issue I am facing is with the design - initially, it shows a buggy design but when I click on the header, it displays the correct design. & ...

Update selection of dropdown menu upon clicking an image

Is there a way to update the select option value by clicking on an image? I have a dropdown list filled with dates from a database as well as two images, one for moving left and the other for moving right. When the left image is clicked, I want to show the ...

Error in parsing string data in Django Chart.js ajax using javascript

I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework. class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

When the request's credentials mode is set to 'include', the 'Access-Control-Allow-Origin' header in the response should not be using the wildcard '*'

I am encountering an issue with my socket.io server as I am unable to connect to it from my local HTML file on my Mac. Error: Failed to load : The 'Access-Control-Allow-Origin' header in the response is causing a problem due to the wildcard ...

Triggering target selection based on the href attribute consistently executing

How can I accurately determine if an anchor tag contains only a "#" in its href attribute? var link = $('#seller-shop').attr('href'); if (link === '#') { alert('I contain #') } else { alert('I do not cont ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

React-redux: There is a TypeError in the code, as _this2.props.handleCityChange is not recognized as

I am currently working on integrating a weather widget in react-redux. I keep encountering the error message "TypeError: _this2.props.handleCityChange is not a function" and similar errors for other functions as well. Despite referring to the redux documen ...

Having trouble transmitting parameters through ajax

I have been attempting to use ajax to send variables to a php page and then display them in a div, but unfortunately, it's not functioning as expected. Below is the HTML code: <div id="center"> <form> ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...