Home > OS >  Vue - open details tag when router-link is active
Vue - open details tag when router-link is active

Time:07-22

I want to give a details tag the attribute open when its child, in this case the <router-link> is active. So I created a details tag..

<!-- ...template -->
        <details>
          <summary
            
          >
            <span >Open</span>
          </summary>

          <nav >
            <router-link
              to="/detail"
              
            >
              <span>Detailview</span>
            </router-link>

            <router-link
              to="/about"
              
            >
              <span>About it</span>
            </router-link>
          </nav>
        </details>

Now I made a function to get all router-links and filter which has the parent/parentNode details. I tested and it works! But now I only wanted the router-link with the inside and it throws errors:

Uncaught TypeError: detail_tags[i] is undefined

<script setup>
import { onMounted } from "vue";
onMounted(() => {
  const detail_tags = document.querySelectorAll("a");
  for (let i = 0; i <= detail_tags.length; i  ) {
    if (
      detail_tags[i].parentElement.parentElement.tagName == "DETAILS" &&
      detail_tags[i].classList.contains("router-link-active")
    ) {
      detail_tags[i].parentElement.parentElement.open = true;
    }
  }
});
</script>

How can I solve this problem to only open the details which child router-link has class router-link-active?

CodePudding user response:

It is the classic "off by 1" error - the elements in Array are counted from 0 so you should not reference an element whose index is equal to or larger than the number of elements in the Array:

for (let i = 0; i <= detail_tags.length; i  ) { // replace the "<=" with "<"

CodePudding user response:

Normally you would use the router as followed

    <div id="app">
      <nav >
        <router-link
          to="/detail"
          
        >
          <span>Detailview</span>
        </router-link>

        <router-link
          to="/about"
          
        >
          <span>About it</span>
        </router-link>
      </nav>

      <!-- component matched by the route will render here, in your case details -->
      <router-view></router-view>
    </div>

I don't think it's wise to deviate from this pattern, you'll probably end up with illogical components.

  • Related