Dynamically update div size on resize

Viewed 36

I'm trying to set a height in px on my container when the size updates. I can display the size as text, and it updates when my container resizes. However, the height attribute on my container does not update.

Js:

setup() {
    const el = ref(null);
    const { height, width } = useElementSize(el);

    return {height, width, el,}
}

Html:

{{ height }}
<div>
  :style="{ height: `${height}px` }"
  ref="el"
>
Resizeable items whoopwhoop
</div>

In this case my {{ height }} updates if I remove the :style attribute, but it says 0px with the :style attribute. How can I fix this?

1 Answers

I am not sure about what useElementSize is.

but if you try this:

<script setup>
import { ref , computed} from 'vue'
const el = ref(null);
  
const height = ref(100);
const width = ref(200);
  
  const dynamicStyle = computed(()=>{
    return {
      height: height.value + "px",
      width: width.value + "px"
    }
  })
</script>

<template>
  <div>
    <input v-model="height" type="number" />
    <input v-model="width" type="number" />
    <div class="resizable"
      :style="dynamicStyle"
      ref="el"
    >
     {{dynamicStyle}}
    </div>  
  </div>
</template>

<style>
  .resizable{
    display: inline-block;
    background-color: royalblue;
  }
</style>

you can modify the size of the element by changing the inputs values.

Here is the Example above.

Related