W
W
wiyod2018-02-26 17:57:13
Vue.js
wiyod, 2018-02-26 17:57:13

Why doesn't addEventListener 'resize' work?

Why can't I change values ​​on resize?
https://codepen.io/kode88/pen/VQEEyy

new Vue({
  el: '#app',
  methods: {
    h () {
      let h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
      return h
    }
  },
  computed: {
    calcViewportHeight () {
       return this.h()
    }
  },
  created: {
    window.addEventListener('resize', this.h())
  }
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-02-26
@wiyod

Firstly, you are trying to set the resize handler not to a method, but to the result of its execution. Secondly - to be honest, I find it difficult to understand what you were counting on, no matter how you pull the height calculation method, what will change for computed? Never mind. You have already been advised to put the result in data, and even showed a working example - I will not add anything here (except that I personally would still put the result in data). If you need a nosebleed without storing the result, then ... well, there is such an option:

<div id="app">
  <h1>{{ h() }}</h1>
</div>

new Vue({
  el: '#app',
  methods: {
    h() {
      return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    },
  },
  created() {
    window.addEventListener('resize', () => this.$forceUpdate());
  },
});

F
fl3nkey, 2018-02-26
@FLUNKEY

window.addEventListener('resize', this.h.bind(this));

or is it better
window.addEventListener('resize', () => this.h());
new Vue({
  el: '#app',
  data: {
    h: 0
  },
  methods: {
    calcH() {
      this.h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    }
  },
  created() {
    this.calcH();
    window.addEventListener('resize', this.calcH.bind(this));
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question