N
N
nurdus2018-12-01 20:33:57
Vue.js
nurdus, 2018-12-01 20:33:57

Is it correct to refer to window and document in vue?

Good evening.
Is it correct to refer to window and document in vue? If not, what is the right way to implement it?
Code example:

// ...
  mounted: function () {
    this.$nextTick(function () {
      this.resize()
    })
    window.addEventListener('resize', this.resize) // 1
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.resize) // 2
  },
  methods: {
    resize: function () {
      this.$store.dispatch('game/setMapSize', document.body.offsetWidth) // 3
    }
  },
// ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
de1m, 2018-12-01
@nurdus

Well, you seem to have done everything right, it looks like it should:

var app = new Vue({
  el: '#app',
  data: function() {
    return {
      msg: 'Hello World! This is a Event listener test.',
      windowWidth: 0,
      windowHeight: 0,
    }
  },

  mounted() {
    this.$nextTick(function() {
      window.addEventListener('resize', this.getWindowWidth);
      window.addEventListener('resize', this.getWindowHeight);

      //Init
      this.getWindowWidth()
      this.getWindowHeight()
    })

  },

  methods: {
    getWindowWidth(event) {
        this.windowWidth = document.documentElement.clientWidth;
      },

      getWindowHeight(event) {
        this.windowHeight = document.documentElement.clientHeight;
      }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getWindowWidth);
    window.removeEventListener('resize', this.getWindowHeight);
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question