I am facing an issue with my Vue.js application. I have a simple root component App
that contains two different components, Room
and Machine
. Both of these components include another component called Datatable
, which is the same for both of them. To switch between Room
and Machine
, I am using dynamic components mechanism. However, each time I change the component, the event is being sent multiple times. According to my understanding, the old component should be destroyed and a new one created when switching, so I'm confused as to why this behavior is occurring.
When I switch between components, the console shows multiple events being emitted: https://i.sstatic.net/sIhDB.png
Here are the components in my application:
App.vue:
<template>
<div id="app">
<select style="padding: 10px" v-model="currentModule" @change="changeComponent">
<option value="Room">Room</option>
<option value="Machine">Machine</option>
</select>
<component :is="currentModule"></component>
</div>
</template>
<script>
import Room from './Room.vue';
import Machine from './Machine.vue';
export default {
name: 'app',
components: {
Room,
Machine
},
data () {
return {
currentModule: 'Room'
}
},
methods: {
changeComponent: function() {
Event.$emit('moduleHasChanged', this.currentModule)
}
},
}
</script>
Machine.vue:
<template>
<div>
Machine template
<datatable></datatable>
</div>
</template>
<script>
import Datatable from './Datatable.vue';
export default {
components: {
Datatable
}
}
</script>
Room.vue:
<template>
<div>
Room template
<datatable></datatable>
</div>
</template>
<script>
import Datatable from './Datatable.vue';
export default {
components: {
Datatable
}
}
</script>
Datatable.vue
<template>
<div>
Datatable
</div>
</template>
<script>
export default {
created() {
Event.$on('moduleHasChanged', (currentModule) => {
console.log(currentModule);
})
}
}
</script>