Vue: Detect when new component is mounted

657 views Asked by At

I'm working on an undo functionality, where a modal pops up in the bottom of the screen after a user clicks the 'delete' button (similar to gmail). Now, I would like to disable the 'delete button' while the undo component is mounted. The undo component and the component where it is shown are unrelated, I am therefore unable to $emit events and would like to avoid using an Event Bus. I know that this.$options.components holds information on the mounted components - so I am basically looking for way to watch changes $options.components Any help is much appreciated!

1

There are 1 answers

0
Nino Filiu On BEST ANSWER

Watching subcomponents internal properties is not really the Vue way, properties like $options are used by plugins and the likes but you should not really use it in your day-to-day code.

Ideally you should have a v-if or an event that links the two but it appears that it is not possible.

Therefore you should share state with Vuex and have conditional behavior based on this shared state. Something like:

// store.js
export default new Vuex.Store({
  state: {
    userCanUndo: false,
  },
  mutations: {
    setUserCanUndo(state, value) {
      state.userCanUndo = value;
    }
  },
}
// Undo.vue
<template>
  <div v-if="userCanUndo">
    <!-- ... -->
  </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
  computed: {
    ...mapState(['userCanUndo']),
  },
}
</script>
// DeleteButton.vue
<template>
  <button :disabled="userCanUndo" @click="delete">
    Delete
  </button>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
export default {
  computed: {
    ...mapState(['userCanUndo']),
  },
  methods: {
    ...mapMutations(['setUserCanUndo']),
    delete() {
      // your delete code here
      this.setUserCanUndo(true);
      setTimeout(() => { this.setUserCanUndo(false); }, 2000);
  }
}