Vue Get DOM Element Styles and Style Change Samples

  • 2021-07-26 06:54:36
  • OfStack

The error of 'style' is not definde may occur when using document to obtain dom node in vue to change the node style. At this time, you can use $refs in mounted to obtain the style and make changes:


<template>
 <div style="display: block;" ref="abc">
  <!-- ... -->
 </div>
</template>
<script>
    export default {
     mounted () {
       console.log(this.$refs.abc.style.cssText)
     }
    }
</script>

The result is display: block;

If we set a full-screen background image for an div, we need to get the screen height and assign it:


<template>
 <div ref="nana">
  <!-- ... -->
 </div>
</template>

<script>
export default {
 mounted () {


     let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
     let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

  this.$refs.nana.style.height = h +'px';

    }

}

</script>


Related articles: