Christian
Christian

Reputation: 26387

Is it possible to get a computed vue variable to change based on viewport size?

I currently have an element that's supposed to change it's position based on the multiple layout elements. I use a computed property for that:

    headerTop(): string {
        if (this.isSmaller) {
            if (window.innerWidth < 682) {
                return "top: 188px;"
            } else {
                return "top: 134px;"
            }
        } else {
            return "top: 44px;"
        }

        return "top: 44px;"
    },

Unfortunately, this variable doesn't refresh when window.innerWidth changes. Is there a way to get it to refresh when window.innerWidth changes?

Upvotes: 1

Views: 1605

Answers (1)

Syed
Syed

Reputation: 16513

I hope, this will get you started:

var app = new Vue({
  el: '#app',
  data: {
    winWidth: 0
  },
  computed: {
    topVal() {
      if (this.winWidth < 682) {
        return '188px'
      } else {
        return '183px'
      }

      // so on, so forth - hope you got the logic
    }
  },
  methods: {
    resizedw() {
      this.winWidth = window.innerWidth;
      console.log(this.winWidth)
    },
  },

  mounted() {
    this.winWidth = window.innerWidth;
    
    // kinda hack to not fire resize event too many times
    var doit;
    window.onresize = () => {
      clearTimeout(doit);
      doit = setTimeout(this.resizedw, 100);
    };
  },
  destroyed() {
    window.onresize = null;
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div :style="{'top': topVal}">resize to check top: {{ topVal }}</div>
  <div>Window Width: {{ winWidth }}</div>
</div>

Upvotes: 3

Related Questions