Search code examples
javascriptvue.jsdomref

How to get _value properties in Vue 3 ref


Hi I'm trying to get values from the _value property in Vue to no avail. How am I able to grab these values like accessKey, align, ariaAtomic etc. I'm trying to get the clientWidth.

enter image description here

  <div id="hello" ref="theRange" class="border-red-200 border-2 w-[80px]">
   <h1>Test</h1>
  </div>

  const theRange = ref(null);
  console.log(theRange.value.clientWidth); // Throws error

Solution

  • This is how you can get it

    <script setup>
    import { ref, onMounted } from 'vue'
    
    const cube = ref(null)
    
    onMounted(() => {
      console.log(cube.value.clientWidth)
    })
    </script>
    
    <template>
      <div ref="cube">nice</div>
    </template>
    
    <style scoped>
      div {
        width: 200px;
        height: 300px;
        background-color: orange;
      }
    </style>
    

    Here is an example.

    enter image description here


    Regarding Vue's lifecycle hooks, setup() doesn't have the element attached to the DOM yet, hence why you may not have anything regarding window-related properties of your object.