Home > Mobile >  How to set DOM element height in Vue 3 script setup (Composition API)?
How to set DOM element height in Vue 3 script setup (Composition API)?

Time:12-15

I'm trying to set a DOM element height to 200px inside script setup:

<script setup>

const element = ref(null)

onMounted(() => {
    element.value.innerHeight = 200
    element.value.height = 200
    element.value.outerHeight = 200
})

</script>

<template>
  <div ref="element" >

    // ...

  </div>
</template>

Although the innerHeight/height/outerHeight of the element ref object are changed, the div element is still rendered with height: auto.

How are DOM element styles in composition api controlled via javascript?

CodePudding user response:

You can't change the height of an element by setting its height/innerHeight/outerHeight. You should update its style properties.

There are 2 methods to choose:

Method 1: set the style directly by js

<script setup>

const element = ref(null)

onMounted(() => {
    element.value.style.height = '200px'
})

</script>

Method 2: Let Vue update the style for you via reactive variables

<script setup>

const elementStyle = reactive({
  height: '100px'
})

onMounted(() => {
    elementStyle.height = '200px'
})

</script>

<template>
  <div :style="{ height: elementStyle.height }">

    // ...

  </div>
</template>
  • Related