Properties of $refs should not be accessed when the component is not mounted

  • VUE_INVALID_REF_ACCESS
  • Error
  • Medium
  • vue

This rule applies when the properties of $refs are accessed when the component is not mounted.

A component is not mounted at the following lifecycles:

  1. beforeCreate()
  2. created()
  3. beforeMount()
  4. destroyed() (Vue 2.x) or unmounted() (Vue 3.x)

If $refs is accessed at the above lifecycles, an undefined or null value is read because the referred element does not exist.

Noncompliant Code Example

View with compliant examples side by side
<template>
  <div ref="x"/>
</template>

<script>
export default {
  beforeCreate() {
    console.log(this.$refs.x); // VUE_INVALID_REF_ACCESS alarm
  }
}
</script>

Compliant Code Example

View with noncompliant examples side by side
<template>
  <div ref="x"/>
</template>

<script>
export default {
  mounted() {
    console.log(this.$refs.x);
  }
}
</script>

Version

This rule was introduced in DeepScan 1.41.0.

See

Was this documentation helpful?