[Vuejs]-Intercepting vue watch event before change happens

0👍

I am not sure that could understand your goal correctly, But if you want to have transition to your button component (that I called "myButton") only if the value of liveModeEnabled prop has been changed, maybe this code can do that for you:

parent component:

<template>
  <div>
    <div class="my-3">
      <button v-on:click="show = !show">
        Toggle
      </button>
    </div>
    <div class="my-3">
      <button v-on:click="funcTrans">
        Toggle-transition
      </button>
    </div>
    <myButton :liveModeEnabled = "show2" :playoutSourceEnabled = "show"></myButton>
  </div>
</template>

<script>
import myButton from '@/components/myButton.vue'
export default {
  name: "parentCompo",
  components: {
    myButton
  },
  data() {
    return {
      show: false,
      show2: false
    }
  },
  methods: {
    funcTrans: function () {
      this.show = !this.show;
      this.show2 = !this.show2;
    }
  }
}
</script>

<style scoped>

</style>

myButton component:

<template>

    <transition :name="transitionEnabled ? 'button-fade' : null">
      <button v-if="shouldShowPlayButton">My button</button>
    </transition>

</template>

<script>
export default {
  name: "myButton",
  props: {
    liveModeEnabled: { type: Boolean, default: false },
    playoutSourceEnabled: { type: Boolean, default: false },
  },
  data() {
    return {
      transitionEnabled: false,
    }
  },
  watch: {
    propArray: function (newArr, oldArr) {
      if (newArr[0] === oldArr[0]) {
        this.transitionEnabled = false;
      } else {
        this.transitionEnabled = true;
      }
    }
  },
  computed: {
    shouldShowPlayButton() {
      return this.playoutSourceEnabled;
    },
    propArray() {
      return [this.liveModeEnabled, this.playoutSourceEnabled]
    }
  },

}
</script>

<style>
.button-fade-enter-active, .button-fade-leave-active {
  transition: opacity 1.5s;
}
.button-fade-enter, .button-fade-leave-to  {
  opacity: 0;
}

</style>

With the code above I watched all props in an array. In this way if one of the props changes the Vue watch is called. After that we check that if the change is related to the desired prop, we set the transitionEnabled to true. But if the desired prop does not change, we set transitionEnabled to false.

Leave a comment