What steps should I take to ensure that the child menus of the v-navigation-drawer component are activated during the initial project launch?

I have created a v-navigation-drawer component with Vue 3 and Vuetify 3.

The v-navigation-drawer functions properly, but I want the child menus to be visible by default without requiring the user's click when the project first launches. I am using v-slot:activator for displaying the child menus. The goal is for users to see the v-navigation-drawer with all the child menu items upon opening the project.

Below is my code snippet-

<template>
  <v-navigation-drawer v-model="drawer" width="325">
    <v-list :lines="false" density="compact" nav >
      <v-list-group v-for="(item, i) in items" :key="i" :value="item" >
        <template  v-slot:activator="{ props }">
          <v-list-item v-bind="props" :prepend-icon="item.icon" :title="item.text" active-color="orange-darken-1"
            rounded="xl" ></v-list-item>
        </template>
        <v-list-item-title v-for="itemdetail in item.subItem" :key="itemdetail.id" :value="itemdetail" >
          <template v-if="itemdetail">
            <v-list-item :prepend-icon="itemdetail.icon" :title="itemdetail.text"
              active-color="teal-darken-1" rounded="xl">
            </v-list-item>
          </template>
        </v-list-item-title>
      </v-list-group>
    </v-list>
  </v-navigation-drawer>
</template>
<script>
export default {
  data: () => ({
    drawer: true,
    items: [{
      text: 'Parent Menu',
      icon: 'mdi-pier-crane',
      subItem: [{
          text: 'Child Menu 1',
          icon: 'mdi-engine'
        },
        {
          text: 'Child Menu 2',
          icon: 'mdi-calculator-variant'
        },
        {
          text: 'Child Menu 3',
          icon: 'mdi-list-status'
        },
        {
          text: 'Child Menu 4',
          icon: 'mdi-calendar-edit'
        },
      ]
    }, ],
  }),
}
</script>

Answer №1

If you want to either open by default or trigger any action, utilize v-model:opened on the list group. Follow these steps:

  1. Start by creating a data property called open.
  2. Add v-model:opened="open" to your list element.
  3. Connect the list group with the text property using :value="item.text"
  4. Since the list group is linked to the text property, set the value of the desired item's text property to the open data property, for example, open: ['Parent Menu']

Here is an example demonstrating this concept:

const { createApp } = Vue
const { createVuetify } = Vuetify
const vuetify = createVuetify()

const app = createApp({
  data: () => ({
    drawer: true,
    open: ['Parent Menu'],
    items: [{
      text: 'Parent Menu',
      icon: 'mdi-pier-crane',
      subItem: [{
          text: 'Child Menu 1',
          icon: 'mdi-engine'
        },
        {
          text: 'Child Menu 2',
          icon: 'mdi-calculator-variant'
        },
        {
          text: 'Child Menu 3',
          icon: 'mdi-list-status'
        },
        {
          text: 'Child Menu 4',
          icon: 'mdi-calendar-edit'
        },
      ]
    }, ],
  }),
}).use(vuetify).mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c6c5d5c4d9d6c9f0839e819e82">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fe9eafaebf6f9e6dfacb1aeb1ad">[email protected]</a>/dist/vuetify.min.css">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d4dddcc6f2849cca">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-card
      class="mx-auto"
      width="300"
      >
      <v-list v-model:opened="open">
        <v-list-item prepend-icon="mdi-home" title="Home"></v-list-item>
        <v-list-group v-for="(item, i) in items" :key="i" :value="item.text" >
          <template  v-slot:activator="{ props }">
            <v-list-item v-bind="props" :prepend-icon="item.icon" :title="item.text" active-color="orange-darken-1"
              rounded="xl" ></v-list-item>
          </template>
          <v-list-item-title v-for="itemdetail in item.subItem" :key="itemdetail.id" :value="itemdetail.text" >
            <v-list-item :prepend-icon="itemdetail.icon" :title="itemdetail.text"
              active-color="teal-darken-1" rounded="xl">
            </v-list-item>
          </v-list-item-title>
        </v-list-group>
      </v-list>
    </v-card>
  </v-app>
</div>

Answer №2

Give this approach a shot:

 onMount() {
    this.$nextTick(() => {
        const groupElements = document.querySelectorAll(".v-list-group");
        for (let i = 0; i < groupElements.length; i++) {
            const group = groupElements[i];
            const content = group.querySelector(".v-list-group__items");
            if (content) {
                group.classList.add("v-list-group--active");
                content.style.display = "block";
            }
        }     
    });
},

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

Utilizing Typeahead for Autocomplete in Durandal: A Step-by-Step Guide

I am attempting to implement an autocomplete input field with typeahead (Twitter Bootstrap) in a modal, but I am encountering difficulties making it function properly. Additionally, this autocomplete field needs to be observable with Knockout so that selec ...

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

Guide to displaying JSON.stringify data in PHP

I am attempting to retrieve my Google contact list using the Contact API. I have successfully retrieved the result and it is displaying in the console of both Chrome and Firefox browsers. However, I want to print this data using PHP on the same page. < ...

I am looking for a way to access an array from Node.js using JavaScript and EJS. How can I achieve this

Currently, I am developing an app that requires passing an array from the server to the client. Initially, I attempted the following: // Server app.get('/', (req,res) => { res.render('index', { data: ["Hello"] }) }) ...

I am attempting to create an API request that is dependent on the outcome of another API request by utilizing a forEach loop. Is there a different approach I could take to achieve the desired

After successfully implementing an API request based on the result of another API request, I am looking for a more efficient method than using forEach for my subsequent API call. Is there a way to achieve this by utilizing Promise.all or any other alternat ...

Encountering an Issue: The program is throwing a TypeError because it is unable to access properties of null when trying to read '

My goal is to upload an excel file using ng-click and the fileUpload($event) function defined in the app controller scope. I am utilizing xlsx to read the file in JSON format, but I encounter an error when running the code: <div> <input id ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

Having issues with unexpected token in Typescript while using "as HTMLElement" type?

I recently started learning Typescript and I encountered an error while using the HTMLElement type in a forEach loop: ERROR in ./app/javascript/mount.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: /Users/me/projects/m ...

Types of Data Encoded in Base64

Within an application I am developing, there is a feature for downloading files that are stored as Base64 strings. It is essential to correctly pair the data types with the corresponding files in order to ensure successful downloads. I thought I had sorte ...

Perform two functions in order using jQuery within a loop

Just dipping my toes in the waters of Javascript. Please go easy on me :) I'm working with two functions that both involve making jQuery requests within for loops. Here's an example: function x(y,z) { for (var i = 0; i < y; i ++) { $.a ...

Testing for connected components with a specific property (React/Redux)

Having a React component with Redux @connect decorator, a situation arises like this: import React, { Component } from 'react' import { connect } from 'react-redux' @connect(mapStateToProps, { onPress: () => {...code}) // The ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

Activate expansive pop-up windows with primeng's dynamic dialog feature

In my Angular web application, I am using the PrimeNg modal extension to display modal popups. I have successfully passed a component to the modal service with the following code: const ref = this.dialogService.open(LogsComponent, { data: { ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Utilize parent function employing component

Is it possible to add a click listener to a component that triggers a method in the parent template using Vue? <template> <custom-element @click="someMethod"></custom-element> </template> <script> export default { ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

Tips for monitoring a field within an angularJS factory

Within my web application, I am utilizing a factory. This factory contains an object named mapLayers. Within my controller, I am assigning this factory.mapLayers object to a variable on the scope called $scope.mapLayers and using ngRepeat to iterate over i ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

Deactivate the dependent picklist functionality on a Visualforce page

After successfully disabling all input and select elements on my page using the following code: $('input').prop('disabled',true); $('select').prop('disabled',true); I encountered an issue with two picklist fields i ...

Testing an async function with Jest - Jest failed to exit within one second of completing the test

Looking to validate the functionality of my Next.js API functions using Jest along with node-mocks-http. The specific function I aim to test is as follows: export default async ( req: NextApiRequest, res: NextApiResponse ): Promise<void> => { ...