vuejs3

Get the height of an element in Vue 3 functional component


I've seen this: Get element height with Vuejs But from my understanding, functional component doesnt have this keyword. How can I get the height of a HTML element in vue. I'm from a React background and would just use refs there but refs in vue dont seem to be the same. Any idea?


Solution

  • Using Vuejs 3 ref to reference a "dom" node element gives access to properties such as clientHeight and clientWidth. The ref will be bound to the element from the onMounted hook and will be null before that (as initialized when defined in sript part). If used in a computed check for null value first or you'll have an undefined property error when accessing clientHeight (for instance).

    Simple example using composition API:

    <template>
        <div>
            <h1>Cool Title</h1>
            <BaseTestData ref="test"></BaseTestData>
        </div>
    </template>
    
    <script setup>
    const test = ref(null)
    
    onMounted(() => {
        console.log(test.value.clientHeight)
    })
    </script>