1

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!

0

1 Answer 1

1

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 };
},

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.