Display the details tag in Vue when the router-link is currently active

I am trying to set the attribute "open" on a details tag when its child, specifically the <router-link>, is active. To achieve this, I have created a details tag...

<!-- ...template -->
        <details>
          <summary
            class="flex items-center"
          >
            <span class="ml-3 text-sm font-medium">Open</span>
          </summary>

          <nav class="ml-5 flex flex-col">
            <router-link
              to="/detail"
              class="flex items-center"
            >
              <span>Detailview</span>
            </router-link>

            <router-link
              to="/about"
              class="flex items-center"
            >
              <span>About it</span>
            </router-link>
          </nav>
        </details>

After creating a function to retrieve all router-links and filter out those that have the parent node as details, I tested it and it seems to work! However, I now want to target only the router-link with the

class="router-link-active"
, but encountered 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>

Any suggestions on how to solve this issue and only open the details element when the child router-link has the class "router-link-active"?

Answer №1

The common mistake often made is the "off by 1" error - the elements in an Array start counting from 0, so make sure not to reference any element with an index equal to or greater than the total number of elements in the Array:

for (let j = 0; j < detail_tags.length; j++) { // change the "<=" to just "<"

Answer №2

Typically, the router is used as shown below:

    <div id="app">
      <nav class="ml-5 flex flex-col">
        <router-link
          to="/detail"
          class="flex items-center"
        >
          <span>Detailview</span>
        </router-link>

        <router-link
          to="/about"
          class="flex items-center"
        >
          <span>About it</span>
        </router-link>
      </nav>

      <!-- The component matched by the route will be rendered here, in this case details -->
      <router-view></router-view>
    </div>

It's not advisable to stray from this structure, as doing so may result in illogical components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

AngularJS animate issue: TypeError - method 'classNameFilter' not found

When I added ngAnimate to my AngularJS app.js file as documented, I encountered a peculiar error: Object [object Object] has no method 'classNameFilter' - angular-animate.js:297 Any idea why this is happening? This is the code snippet where I ...

Using NodeJS to extract information from Opendata JSON files

I'm currently working on a project that involves fetching JSON data from an Open Dataset using NodeJS and passing it to angular. The challenge I'm facing is that I'm receiving a JSON file instead of a JSON object, which makes it difficult to ...

Searching for values in an array using the $elemMatch operator in MongoDB 2.6 without the need for the $eq operator

Looking to retrieve all users with a specified objectId in an array. Here is the query I'm using: var query = { 'arrayOfIds': { $elemMatch: { $eq: id } }, }; This query functions well in mongodb 3.0. However, in mongodb 2.6, there isn& ...

Tips for creating an auto-incrementing ID within Firebase's real-time database

How can I create an automatic incrementing ID for entries in a Firebase database? The first item should have an ID of 1, and the second one should be 2. var database = firebase.database(); var userDetails = database.ref("Article"); userDetails. ...

Is there a way to match a compressed javascript stack trace with a source map to pinpoint the correct error message?

When managing our production server, I have implemented minified javascript without including a map file to prevent users from easily deciphering errors. To handle angular exceptions caught by $exceptionHandler, I developed a logging service that forwards ...

Detecting the clicked link within a React component

My NavBar features a Logo that includes a Link to the Home page "/". The application kicks off from the main page and as per user selections, the UI will adapt accordingly. To offer users a chance to reset everything if they are currently on the Home compo ...

The Javascript code I wrote is unable to detect the array element that was initially defined in Python

Trying to launch a new browser window through Selenium using driver.execute_script("window.open('');") However, the goal is to open a specific link provided by the user. For this purpose, extracted the link input from an array and inc ...

Concealing elements using react navigation

Just diving into React.js and I've got a question regarding react router. I'm a bit confused about nested routes in react router. Let's say we have the following code snippet (taken from react-router's github page) <Router> < ...

Is there a way to enable Fancybox to change to the adjacent gallery by simply using the 'up' or 'down' arrow keys?

I am currently working on a layout that consists of a vertical column of thumbnail images, each linked to its own gallery with additional images. When the user clicks on a thumbnail image, Fancybox opens, allowing them to navigate through the images within ...

Retrieve the data from a Sequelize Promise without triggering its execution

Forgive me for asking, but I have a curious question. Imagine I have something as simple as this: let query = User.findAll({where: {name: 'something'}}) Is there a way to access the content of query? And when I say "content," I mean the part g ...

Activate the SHIFT key

In the input field for user's firstname, I have restricted all keys to a-z and 0-9 only. This restriction is working well, but I also want to allow the SHIFT key so that users can capitalize letters if needed. Despite trying various solutions, I have ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

Leveraging the AngularJS model within a tabset framework

I am working with a tabset that has two options and I am binding data from a JSON file using Angular. What I would like to do is log the name of the tab that I click on to the console. I thought about using a "model" for this, but I am not sure if that is ...

Tips for retrieving the user-input value from an HTML text field

Exploring the world of JS, I set out to create a basic calculator after just one week of lessons. However, I hit a roadblock when trying to extract user-input values from my HTML text fields. Here's a snippet of my html: <div class="conta ...

Using Vue.js to submit a form in Laravel and redirecting with a flash message

I am facing an issue where I have two components named Index and Create, loaded from separate blade files. The challenge is passing a flash message as a prop between these components due to their file separation. How can I redirect after submitting a form ...

Easily modify and manage state on-the-fly using TextFields

Is the title conveying my intentions clearly? If not, please let me know. Essentially, I am looking to create a component that generates a form based on a JSON file. For example, if someone clicks on "light" in the navbar, I want the form to display fields ...

Why isn't the PHP snack bar working when clicking on an href <a> using onClick?

How can I dismiss this snackbar when the add to cart <a href> is clicked? I've tried but nothing seems to work. Can anyone provide some assistance? Here is my code: SNACKBAR CODE <div id="snackbar">Some text some message..</div> A ...