[Vuejs]-Vue: emit to view component works only the first time

0👍

Your code should work, As I am not able to setup the Vue 3 in the below code snippet. I am demoing it using Vue 2 setup. Please have a look and try to find out the root cause of the issue you are facing.

Every time you will click on Click Me text in the inner child component. It is emitting the events properly.

Vue.component('childComponent', {
  template: `<div class="emit-time" @click="click()">Click me (Component A)</div>`,
  methods: {
    click() {
      console.log('component A');
      this.$emit('clickup', 'a click');
    }
  }
});

Vue.component('ParentComponent', {
  data() {
    return {
      message: null
    }
  },
  template: `<div><p v-text="message"></p><child-component @clickup="localMethod"></child-component></div>`,
  methods: {
    localMethod() {
      console.log('component B');
      this.message = 'Component B invoked and emitted the event to the parent';
      this.$emit('clickup', 'a click');
    }
  }
});

new Vue({
  el: "#app",
  data: {
    message: null
  },
  methods: {
    localMethod() {
      console.log('Root component');
      this.message = 'Top most parent invoked'
    }
  }
});
#app {
  padding : 20px;
}
div {
  padding : 10px;
  border : 1px dashed black;
}
div ~ div {
  margin-top : 10px;
  border-color : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p v-text="message"></p>
  <parent-component @clickup="localMethod"></parent-component>
</div>

0👍

Your code should work as it is. I have set up a demo here and it is working just fine. Maybe you can match your code with this-

View.vue

<script setup>
import Comp1 from './Comp1.vue'

const setReactive = (payload) => {
  console.log('View', payload);
};
</script>
<template>
  <v-app>
    <v-main>
      <Comp1 @change-parent-reactive-data="setReactive" />
    </v-main>
  </v-app>
</template>

Component 1

<script setup>
import Comp2 from './Comp2.vue'
  
const emits = defineEmits(['changeParentReactiveData'])
    
const emitToParent = (payload) => {
  console.log('Component A', payload);
  emits('changeParentReactiveData', payload);
};
</script>
<template>
  <Comp2 @change-parent-reactive-data="emitToParent" :some-prop="262194"></Comp2>
</template>

Component 2

<script setup>
const props = defineProps(['someProp']);
const emits = defineEmits(['changeParentReactiveData'])
  
const emitToParent = () => {
  console.log('Component B', props.someProp);
  emits('changeParentReactiveData', props.someProp);
};
</script>
<template>
  <v-btn @click="emitToParent()">
    click
  </v-btn>
</template>

-1👍

Try implementing a global event bus to pass values from component to component.
Here’s a blog to explain how:
https://blog.logrocket.com/using-event-bus-in-vue-js-to-pass-data-between-components/

Leave a comment