Sebastien D
Sebastien D

Reputation: 4482

Vuejs: autofit div according to remaining space in window

Within vueJs (2.5.16) I'm trying to set the style property of a div so it auto fit the remaining space of a window depending of its size:

enter image description here

I intended to use a computed value which would give me live the correct height and bind it into the style property of the wanted div:

Vue.component('menus', {
    template: '<div id="menu-div">MY MENU</div>'
});

Vue.component('expandable', {
    template: '<div id="expandable-div" :style="{height:expandableHeight}">EXPANDABLE<div>{{expandableHeight}}</div></div>',
    computed: {
        expandableHeight() {

            return ($(window).height() - $("#expandable-div").position().top) + 'px'

        }
    }
});

var vm = new Vue({
    el: '#app'
});

fiddle

Using $(window).height() and $("#expandable-div").position().top from jQuery I thought I could achieve a result since it works in my console.

Unfortunately I have an error:

TypeError: Cannot read property 'top' of undefined

Upvotes: 0

Views: 1443

Answers (1)

Vucko
Vucko

Reputation: 20834

Why not use CSS's flexbox to achieve that?

Vue.component('menus', {
  template: '<div id="menu-div">MY MENU</div>'
});

Vue.component('expandable', {
  template: '<div id="expandable-div">EXPANDABLE<div>foo</div></div>',
  computed: {}
});

var vm = new Vue({
  el: '#app'
});
body {
  margin: 0;
}

#app {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

#menu-div {
  height: 50px;
  background: #768ffb;
  margin-bottom: 5px;
}

#expandable-div {
  background: #76fbc1;
  flex-grow: 1;
}
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <menus></menus>

  <expandable></expandable>
</div>

Upvotes: 2

Related Questions