Search code examples
vue.jsref

I need help about the ref tag of vue.js


I'm a novice.And I introduced vue.js file.Why would I report an error?

ERROR:Cannot read properties of undefined (reading 'element')

......
<script type="text/javascript">
        window.onload = function () {
            let height = this.$refs.element.offsetHeight;
            console.log(height)
        }
</script>
......
<nav ref="element">......</nav>
......

Solution

  • In your case "this" is referring to the Vue instance.

    To access "this" you need to use it inside any hook of Vuejs where you would have access to "this".

    On another hand, use arrow functions because arrow functions do not have their own "this" instance, therefore, arrow functions can use global "this" and in your situation global "this" would be the Vue instance.

    For example, you can write this code inside the "mounted" hook like this-

    mounted() {
        window.onload = () => {
            let height = this.$refs.element.offsetHeight;
            console.log(height);
        };
    },