Saeed
Saeed

Reputation: 2299

Watch height of an element in VueJS

Is there any way to set a watcher on the height of an element in VueJS?

I am trying to fix the filters part on a search result page. but if the results change there is no way to find about it and unfix the filters.

Upvotes: 17

Views: 39000

Answers (4)

Seetpal singh
Seetpal singh

Reputation: 3857

<script setup>

const list = ref([
    'sdg sdfg sdfhs fhseraj sdhbfjasvfkjvaskjvfuas', 
    'ggs dfg s', 
    'sdg s sfg sfgs dfg'
])

const itemRefs = ref([])

onMounted(() => {
   alert(itemRefs.value[1].clientHeight)
})

</script>


<template>
  <ul style="width: 50px">
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

Upvotes: -1

Eli Zatlawy
Eli Zatlawy

Reputation: 1022

If you are want to observe an element inside a component then use an arrow function:

observeHeight() {
      const resizeObserver = new ResizeObserver(() => {

        console.log('Size changed:', document.getElementById('elementId').clientHeight;);
      });

      resizeObserver.observe(document.getElementById('elementId'));
    }

Upvotes: -1

Paul
Paul

Reputation: 863

You could use the ResizeObserver and integrate it into your Vue-Component

function observeHeight() {
  const resizeObserver = new ResizeObserver(function() {
     console.log("Size changed");
  });

 resizeObserver.observe(document.getElementById('yourId'));
}

function changeHeight() {
  var elem = document.getElementById('yourId');
  
  console.log('...loading data...')
  setTimeout(function(){ 
    elem.style = "height: 200px";
  }, 3000);
  
}

observeHeight();
changeHeight();
#yourId {
  background-color: beige;
  height: 100px;
}
<div id="yourId">
  
</div>

Upvotes: 30

jparaya
jparaya

Reputation: 1339

You can get the height with $ref.yourElement.clientHeight, after the search result returns the data. With that, you can set the height as part of your data{} section, and from there apply a watcher. Check this example

new Vue({
  el: '#app',
  data: {
    height: 0
  },
  methods: {
    calculateHeight() {
      this.height = this.$refs.app.clientHeight;
    }
  }
});

Upvotes: 10

Related Questions