MOHAMED AZARUDEEN
MOHAMED AZARUDEEN

Reputation: 171

Trigger Window Resize Event Listener from another Component - Vuejs

I have created two Components Component1 and Component2. In the Component1 I have registered window resize event (Whenever the page is resizing, it is getting triggered). I want to invoke this resize event from Component2.

Component1:

export default {
    name: 'Component1',
    async mounted() {
       window.addEventListener('resize', this.windowResize);
    },
    methods: {
       windowResize() {
          console.log("Window Resize event called")
       }
    }
};

Component2:

export default {
    name: 'Component2',
    methods: {
       doResize() {
         // Need to invoke Component1 Resize from here
       }
    }
};

Note: These are not connected through the root vue instance.

I have tried the following but not worked,

Component1:

mounted() {
    this.$root.$on('Component1', () => {
        // your code goes here
        this.windowResize()
    }
}

Component2:

...
doResize(){
 this.$root.$emit('component1') //like this
},

Kindly help me to figure out this.

Upvotes: 1

Views: 1427

Answers (1)

tao
tao

Reputation: 90068

methods: {
  dispatchWindowResize() {
    window.dispatchEvent(new Event('resize'))
  }
}

Calling this.dispatchWindowResize() inside that component will dispatch a new window.resize event on window object, which will run all listeners added to it from any source, including the ones added by other components in your app.

Documentation:

Test:

const Emitter = Vue.defineComponent({
  template: '#emitter-template',
  methods: {
    dispatchWindowResize() {
      window.dispatchEvent(new Event('resize'))
    }
  }
})
const Receiver = Vue.defineComponent({
  template: '<div></div>',
  mounted() {
    window.addEventListener('resize', this.logResize)
  },
  methods: {
    logResize() {
      console.log(`window.resize: {w: ${window.innerWidth}, h: ${window.innerHeight}}`);
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.logResize)
  }
})

new Vue({
  el: '#app',
  components: { Emitter, Receiver }
})
<script src="https://v2.vuejs.org/js/vue.min.js"></script>
<div id="app">
  <receiver></receiver>
  <emitter></emitter>
</div>
<template id="emitter-template">
  <button @click="dispatchWindowResize">Dispath window resize</button>
</template>

<Receiver /> receives all resize events: the ones triggered by resizing the browser window and the ones triggered by clicking the button inside <Emitter />

Upvotes: 2

Related Questions