ぬまのどろ

namazuのゆるい日記。 ゆるり更新。

Vueでwindow.innerWidthをリアクティブにしときたい

しょうもな日記ネタ。 モバイル環境向け。

window.innerWidthが必要なんだよなぁ。。。 あーーー。。。 うーーん。。。。。。。 ってときに

あーー window.innerWidhtがリアクティブだったらいいのになー あーー なんでこいつReflowするんだろう。。。 What forces layout/reflow. The comprehensive list. · GitHub

って思いながら 面倒だから画面回転とか対応せんでもいいか。 resizeはスクロールで起きてジャンクするの嫌だし無視しとこ。。。

っていつもしていたのですが。

一念発起してちょっとやってみた。

const windowEnvWatcher = new Vue({
  name: 'window-env-watcher',
  data () {
    return {
      innerWidth: window.innerWidth,
      innerHeight: window.innerHeight
    };
  },
  created () {
    window.addEventListener('orientationchange', () => {
      [this.innerWidth, this.innerHeight] = [this.innerHeight, this.innerWidth];
    });
  }
});

export const windowInnerWidth = windowEnvWatcher.innerWidth;
export const windowInnerHeight = windowEnvWatcher.innerHeight;

orientationchangeが走るのはAndroidiOSでresize後か前か問題がありますがこの実装なら問題ない。 ありとあらゆるところからコレを参照してもリフローは起きない。

よさげ?