Home > Net >  Trying to replace getElementByID with refs in vue 3 won't work
Trying to replace getElementByID with refs in vue 3 won't work

Time:08-30

What I'm Trying to do

I am new to Vue and I'm trying to replace getElementByID with $refs, but I get the following error:

Errors

Console Errors

Code

Here is the HTML:

<router-link to="/" ref="navOpt">
    <div ref="activeOpt">

Here is the script:

// imports
import { ref, onMounted } from "vue";

// setup
setup() {
  let navOpt = ref();
  let activeOpt = ref();
  onMounted(() => this.$refs.navOpt);
  onMounted(() => this.$refs.activeOpt);
  return { navOpt, activeOpt };
},

// Methods - check if the navOpt is active and removes css if it is
checkActiveRoute() {
  if (this.navOpt.classList.contains("router-link-active")) {
    this.activeOpt.classList.remove("hide-active");
  }
},

// Created - call method on load
created() {
  this.checkActiveRoute();
},

Tried Solutions

I have tried this but it gave me the same error.

Can someone help with this? Thanks!

CodePudding user response:

ref values are automatically bound to the ref attribute in your elements, and there's no need to do onMounted(() => this.$refs.navOpt) since this doesn't have any effect, you should also use only one API (composition or options), but it's recommended to use the composition API, finally define the method just a function which should be called in the onMounted hook :

setup() {
  let navOpt = ref();
  let activeOpt = ref();
  onMounted(() => {
     checkActiveRoute()
   });

function checkActiveRoute() {
  if (navOpt.value.classList.contains("router-link-active")) {
        activeOpt.value.classList.remove("hide-active");
  }
}
  return { navOpt, activeOpt };
},

  • Related