Enhance the appearance of unordered lists within list items using Vue.js for added style

I'm currently encountering an issue on how to apply styling to a ul element inside a clicked li using Vue JavaScript. Here is my HTML code:

<ul>
   <li>Menu</li>
   <li @click="toggleSubMenu">Profile
      <ul> //Add class here
          <li>History</li>
      </ul>
   </li>
   <li @click="toggleSubMenu">Media
      <ul :class="{ 'd-block' : data.sub_menu_show}">
          <li>Photos</li>
          <li>Videos</li>
      </ul>
   </li>
</ul>

Here is my Vue code:

<script>
import { reactive } from 'vue'

export default {
    setup(){
        const data = reactive({
            sub_menu_show: '',
        });

        const toggleSubMenu = () => {
            data.sub_menu_show = !data.sub_menu_show
        }

        return{
            data,
            toggleSubMenu
        }
    }
}
</script>

My goal is for the styling applied by toggleSubMenu to only affect the ul inside the clicked li, and not all ul elements or other sub menus. Any suggestions or help would be greatly appreciated.

Thank you in advance.

Answer №1

Presently, you are managing multiple UI elements using a single state. How about reorganizing it like this:

<ul>
   <li>Menu</li>
   <li @click="() => toggleSubMenu('profile')">Profile
      <ul :class="{ 'd-block': toggleStates['profile'] }">
          <li>History</li>
      </ul>
   </li>
   <li @click="() => toggleSubMenu('media')">Media
      <ul :class="{ 'd-block': toggleStates['media'] }">
          <li>Photos</li>
          <li>Videos</li>
      </ul>
   </li>
</ul>
<script>
import { ref } from 'vue'

export default {
    setup(){
        const toggleStates = ref({ profile: false, media: false });

        const toggleSubMenu = (type) => {
            toggleStates.value[type] = !toggleStates.value[type];
        }

        return {
            toggleSubMenu,
            toggleStates
        }
    }
}
</script>

Answer №2

The @click attribute serves as a convenient way to implement the v-on directive in Vue. When used, this Vue directive automatically provides an event argument containing various details, such as the target element, to the designated callback function.

As a result, you can directly manipulate the specified target element.

event.target.style.cssText = ''

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

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...

Preventing nested prototype methods from being transferred between objects in a WebWorker

My challenge is to reserialize an object from a WebWorker while maintaining the same definitions. However, upon receiving the message, all of the prototype functions are lost. The current solution I have only works for first level prototype functions, bu ...

Efficient AJAX validation using PHP and JavaScript

I am currently working on a small website project that requires User registration functionality. One key aspect is ensuring that the system prevents users from registering with usernames that are already in use. Most modern websites employ AJAX to verify ...

Component for numbering pages, utilize array mapping to locate route

I'm currently working on creating a component for page numbers using an array of objects that includes a path and an ID. import React from 'react'; export function PageNumber(props) { const pageData = [ {path: '/calc/1', id:1}, ...

Extracting data from a Firebase realtime database JSON-export is a straightforward process that can be

I'm currently working with a Firebase realtime database export in JSON format that contains nested information that I need to extract. The JSON structure is as follows: { "users" : { "024w97mv8NftGFY8THfQIU6PhaJ3" : { & ...

Preventing CSS blocking with Node on Heroku by using X-Content-Type-Options

I am facing a challenge deploying my Node.js application to Heroku. The frontend of the app is built using Vue.js and the Vue build output is located within the /public directory of the Node app. While everything functions perfectly when accessed from loca ...

Are HTML5 Track Element Cue Events Working Properly?

My goal is to dynamically assign functions to HTML5's cue.onenter events. This feature is relatively new and currently only supported in Chrome with specific flags enabled (Refer to the example on HTML5 Rocks here). However, I seem to be facing some ...

Conditionally render a Vue component as a modal when the specified route metadata key is set to true

Currently, I am using vue-router and attempting to implement a specific functionality: The goal is to define within the router routes whether a component should be displayed in a modal or not. If rendered in a modal, all components beneath it (under modal ...

The tooltip is being truncated

https://i.sstatic.net/o41Qz.png Struggling with a tooltip that keeps getting cut off? I've tried everything and still can't get it right. <th class="fd-table--header-cell" scope="col"> <p class=&q ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

What is the best approach to adding components dynamically in AngularJS?

Can someone explain how to create a component in a controller? I already have an AngularJS module with a controller defined: let app = angular.module('testApp', []); However, when I try to load the component, it does not work as expected. app ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

What is the best way to align a collection of search bars with HTML and CSS?

Can someone help me align my search bars and submit buttons? I'm new to HTML and struggling with this task. (By the way, this is just a small part of the browser layout, it doesn't usually look so messy!) .center-block{ margin-top: 220px; ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Fixing display flex with columns of percent width and 1px gap: A step-by-step guide

When displaying flex columns with percent width on a specific width, make sure to leave a 1px gap between them. Check out the screenshot here html, body { margin: 0; padding: 0; } * { box-sizing: border-box; } .wrapper { max-width: 1200px; p ...

Avoid being redirected to another page after submitting the form, instead remain on the current page

Unable to understand why this functionality is not working the way it is supposed to... In my ASP.NET MVC5 form, I have two buttons - "Add New Product" which allows users to temporarily save product data (not to the database) and input information on anot ...

Is it possible to utilize the Linear-gradient property for creating a vertical background color effect?

I'm currently attempting the following: body { height:100%; background: -moz-linear-gradient(left, #DB2B39 50%, #2B303A 50%); background: -webkit-linear-gradient(left, #DB2B39 50%,#2B303A 50%); background: linear-gradient(to right, #D ...

What sets apart using import './style.scss'; in main.ts from the css.preprocessorOptions configuration?

Check out the demo here: https://stackblitz.com/edit/vitejs-vite-qzqife?file=src/style.scss This is the content of style.scss: $color: red; Within main.ts file: import './style.scss'; Encountering an error when using $color in <style lang=& ...

The act of linking an SVG image from the same SVG file can result in the disappearance

Can anyone help me figure this out? I'm facing a strange issue: <svg aria-hidden="true"> <use xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#down"></use> </svg> <table> <tr> <td> ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...