Learn how to showcase the chosen <li> item in a dropdown menu within a Vuejs environment

I have successfully implemented a dropdown menu using ul and li elements. Through a for loop, I was able to dynamically generate the li elements. The class nav-is-visible helps in displaying the li elements when the user clicks on the dropdown menu. However, I am facing difficulty in figuring out how to display the currently selected value. Below is an excerpt of my code:

Update: Here's the link to my updated codepen: https://codepen.io/Issaki/pen/OYxbJV

Update: I am still struggling with this issue, any assistance would be greatly appreciated.

  <template>   
  <div>
    <nav :class="{'nav-is-visible' : displayCategory}">
      <ul>
        <li v-for="item in items" :key="item.id" @click="displayCategory = !displayCategory">
          <p>{{item.name}}</p>
        </li>
      </ul>
    </nav>
  </div>
</template>


<script>
export default {
  data() {
    return {
      displayCategory: false,
      items: [
        {
          id: 1,
          name: "Basketball"
        },
        {
          id: 2,
          name: "Soccerr"
        }
      ]
    };
  },

  methods: {
  },
  computed: {}
};
</script>

<style>
nav {
  width: 100%;
  top: 90px;
  left: 0;
  z-index: 3;
  height: 45px;
  line-height: 45px;
  vertical-align: middle;
  display: inline-block;
  font-size: 0.1px;
  font-weight: 300;
  font-style: normal;
  cursor: pointer;
  padding: 0;
  cursor: pointer;
  transition: opacity 0.25s ease-in-out;
  -moz-transition: opacity 0.25s ease-in-out;
  -webkit-transition: opacity 0.25s ease-in-out;
}

/* Create the bordera and the surrounding */
nav ul {
  height: 45px;
  padding: 0 10px;
  text-align: left;
  border: 1px solid #33383b;
  background: #fafafa;
  border-radius: 3px;
}

nav ul li {
  display: block;
  position: relative;
}

nav ul li:first-child:before {
  position: absolute;
  content: " Menu ";
  position: relative;
  font-size: 1.6rem;
  font-size: 16px;
  font-weight: 600;
  text-transform: uppercase;
}
nav ul li:first-child:after {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 12px;
  font-size: 1.2rem;
  content: "\f0d7";
  color: #2267b9;
  padding-right: 10px;
}

/* Hide the li elements */
nav p {
  display: none;
  font-size: 1.5rem;
  font-size: 15px;
  text-decoration: none;
  text-transform: uppercase;
  color: #4a5564;
}

#category-btn {
  display: none;
}

.category-input {
  display: none;
}

nav.nav-is-visible ul {
  height: initial;
  background: #f1f1f1;
}

nav.nav-is-visible ul li:first-child:after {
  content: "\f00d";
}
nav.nav-is-visible ul li p {
  display: block;
  border-bottom: 2px solid #f1f1f1;
}
nav.nav-is-visible ul li p:hover {
  border-bottom: 2px solid #4a5564;
}
nav.nav-is-visible ul li:last-child {
  margin-bottom: 10px;
}

/* Make button visible again when nav-is-visible class is toggled */
nav.nav-is-visible #category-btn {
  display: block;
}
</style>

Answer №1

It is essential to:

  • store the item you clicked on.
  • apply a conditional class to the list item based on whether the selectedId matches the item id.
<template>
    <div>
        <nav :class="{'nav-is-visible' : displayCategory}">
            <ul>
                <li v-for="item in items" :key="item.id" @click="select(item.id)" :class="selectedId === item.id ? 'my-selected-item-class':null">
                    <p>{{item.name}}</p>
                </li>
            </ul>
        </nav>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                selectedId : null,
                displayCategory: false,
                items: [{id: 1,name: "Basketball"},{id: 2,name: "Soccerr"}]
            };
        },
        methods: {
            select(itemId){
                this.selectedId = itemId
                this.displayCategory = !this.displayCategory
            }
        }
    };
</script>

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

What is the best way to incorporate multiple fonts from react-native-vector-icons into a single file?

Is it possible to incorporate multiple fonts, such as FontAwesome and Entypo, from react-native-vector-icons into a single file? ...

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

Issue: It is necessary to return a valid React element (or null) in the code (Verify Return() and Render())

After making some changes to my code, I started encountering the following error... PartnersIteration.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object. Despite reviewing ...

Is it possible to create Vue apps using TypeScript with just Babel?

Is there a way to compile and construct my TypeScript Vue application using only Babel? After extensively utilizing vue-cli-service, I've come to the point where I require a more minimal setup, eliminating the need for webpack or any other similar too ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...

The system is facing difficulty in accessing the property 'user_first_name' as it is currently undefined

I'm having trouble registering a user with expressjs/mongoose as I keep receiving the error: TypeError: Cannot read property 'user_first_name' of undefined at C:\Quiz webPolitica\server.js:20:24 at Layer.handle [as handle_request] ...

Implement a hover effect on an image

Hey there! I'm in the process of creating my own website and I want to add a cool front page design. However, I'm unsure how to make it work. This is what the normal version looks like: https://i.sstatic.net/QM0c0.png (Try copying and pasting i ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

Filtering out section boxes does not eliminate empty spaces

Link to Fiddle I've run into a bit of a roadblock while trying to filter my section box for a project I'm currently working on. The issue I'm facing is that instead of collapsing the first section box to display only the filtered options, i ...

Most efficient method to retrieve a specific element from an array without the need for iteration

Within one of the controllers in my Angular application, I have set a variable like this: SomeService.get({}, function(data){ // This assigns xyz as the data list retrieved from the // resource within the controller's scope $scope.xyz = ...

ag-grid highlights checkbox when cell is chosen

Is there a way to navigate a column of checkboxes using the down arrow key and toggle a checkbox with the spacebar? Instead of selecting rows, I just want to be able to edit the checkbox in the current row. I have created a custom cell renderer, but I ne ...

Issues encountered while trying to connect Laravel API with Vue (Nuxt.js) application running in a Docker environment

Currently, I am in the process of developing a Nuxt.js application that needs to communicate with a backend API built on Laravel. The issue I'm facing is that every request sent to the API using axios results in one of the following errors (depending ...

Error encountered: Server.js failed due to the presence of an unexpected token

I am in the process of developing a web application using the MEAN stack and I am currently testing my nodejs server. Below is an excerpt from my server.js file: // server.js 'use strict'; // modules ================================ ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

What is the process for integrating tailwindcss into a vite project?

I have recently started using vite version 0.16.6 and I am looking to transition a vuepress website to utilize vite. The main challenge I am facing is figuring out how to set up tailwindcss with vite. In my CSS file named index.css @tailwind base; @tail ...

Display an alert message through jQuery script if the input type file is not an image

When working with an input type file, if an image is selected it will show a preview. If something other than an image, like a PDF or DOCX file, is selected I want to show an alert as invalid. However, I am encountering an error: Cannot read property &apos ...

Unable to add new Instance Properties in Vue.js within a Laravel project

I am attempting to develop a localization property similar to __('text') in Laravel blade template. I have set up a global window variable that contains all required data under the name window.i18n Below is my resourses/js/app.js file: require(& ...

Oops! Issue detected: improperly configured csrf in Express JS 4

Seeking help to activate the csrf module within Express 4 for an existing project. This is the code I've implemented: var csrf = require('csurf') ... app.use(csrf()); Upon starting my application, I encounter this message: Error: miscon ...

Custom Angular filter for comparing two numbers within an ng-repeat loop

Our Angular project involves working with an array named data that contains: $scope.data= [ {_id: '1', rev: 1-bar}, {_id: '2', rev: 2-bar}, {_id: '3', rev: 3-bar}, {_id: '4', rev: 4-bar}, {_id: ...