Home > database >  this.$emit() is not a function while trying to change state in parent component from child in compos
this.$emit() is not a function while trying to change state in parent component from child in compos

Time:04-03

//Parent component

<template>
   <childComp @onchangeData='changeData' />
</template>
<script>
   setup() {
   const state = reactive({
     data: 'anything
   });
    
   function changeData(v){
     state.data = v
   }
   return { changeData}
},
</script>

//Child

<template>
 <button @click='change('hello')' />
</template>

<script>
   setup() {

   function change(v){
     this.$emit('onchangeData', v)
   }
   return{change}
},
</script>

I am struggling to change the parents' reactive state from the child's button click. It's saying this.$emit is not a function. I tried many ways like using @onchangeData='changeData()' instead of @onchangeData='changeData', using arrow functions etc. But nothing works. Here, I wrote an example and minimal code to keep it simple. But I hope my problem is clear.

CodePudding user response:

Look at following snippet, this is not the same in composition as in options API, so you need to use emit passed to 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>

CodePudding user response:

Parent Component:

<template>
   <childComp @onchangeData='changeData' />
</template>
<script>
export default {
   methods: {
     changeData(v){
       this.state = v
     }
   },
   data() {
    return {
      state: null,
   },
};
</script>

Child Component:

<template>
 <button @click='change('hello')' />
</template>

<script>
export default {
   methods: {
     change(v){
       this.$emit('onchangeData', v)
     }
   }
};
</script>
  • Related