Tips on how to toggle/close a dropdown menu that is displayed on a different page using Vue

Below is a screenshot of my cart dropdown: https://i.sstatic.net/IdOZK.png

The issue I am facing is that the cart stays open even when I navigate to another page. I need it to close when I move to a different page. Below is my component code:

<template>
    <div class="custom-select" :tabindex="tabindex" @blur="open = false">
        <div class="selected" :class="{ open: open }" @click="open = !open">
            {{ selected.name }}
        </div>
        <div class="items" :class="{ selectHide: !open }">
            <div v-if="defaultValue != ''">{{ defaultValue }}</div>
            <div v-for="(option, i) of options" :key="i"
                 @click=" selected = option; open = false; $emit('input', option);">
                {{ option.name }}
            </div>
        </div>
    </div>
</template>


<script>

export default {
    props: {
        options: {
            type: Array,
            required: true,
        },
        defaultValue: {
            type: String,
            required: false,
            default: "Choose an option",
        },
        tabindex: {
            type: Number,
            required: false,
            default: 0,
        },
    },
    data() {
        return {
            open: false,
            selected: this.setDefaultValue(),
        };
    },
    mounted() {
        this.$emit("input", this.selected);
    },
    methods: {
        setDefaultValue() {
            if (this.defaultValue == '' && this.options.length > 0) {
                return this.options[0];
            }
            return {name: this.defaultValue};
        }
    }
};
</script>

I welcome any suggestions or solutions to resolve this particular problem.

Answer №1

If you want to implement a functionality where the menu closes when you click outside of it, you can create a custom directive in Vue.js. This directive will trigger a close menu function whenever a click event occurs outside the menu area. Additionally, you can also call the close menu function when any action within the menu is clicked.

Here's an example of how you can define this directive in your main.js file:

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      // Check if the click occurred outside the element and its children
      if (!(el === event.target || el.contains(event.target))) {
        // Call the specified method to close the menu
        vnode.context[binding.expression](event)
      }
    }
    document.body.addEventListener('click', el.clickOutsideEvent)
    document.body.addEventListener('touchend', el.clickOutsideEvent)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
    document.body.removeEventListener('touchend', el.clickOutsideEvent)
  }
})

To use this directive in your menu component, simply add the 'v-click-outside' attribute with the name of the close menu function as its value:

<div v-click-outside="closeMenu"></div>

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

When updating a value using v-model, the entire table is refreshed

As I was working on creating an editable table, I noticed a significant slowdown in performance once the number of rows exceeded 100. This prompted me to investigate the issue further. In the scenario below, every time the input value is changed, the enti ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Managing time and time discrepancies live in VueJS

I am trying to calculate the elapsed time from the order time in Vue, but I keep getting a warning message that says: [Vue warn]: You may have an infinite update loop in a component render function. Can anyone recommend the correct approach to tackle this ...

By simply clicking a button, you can input a value into a field without the need for the page to refresh

Can someone please help me figure out how to insert a specific value into an input field without refreshing the page? I have tried the following code but it doesn't seem to work. Basically, when I click the button, I want the value "1234567" to be aut ...

Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript: // Function to add a new account row if (tit.innerHTML === "Add Account"){ var table = document.getElementById(tableId); var row = table ...

Card image floating to the right using Bootstrap

I have a set of three horizontal cards, not in a card deck as it's not responsive, and I want to align images in the bottom right corner of each. Bootstrap 4 comes with a class for card-img-left which works perfectly. I've attempted using float-r ...

JSON script containing the variable "url"

After spending days messing around, I've been learning javascript and jquery for a few weeks now. It's been going well, but there are some hurdles... For a mobile app I'm working on, I'm trying to retrieve the coordinates. Displaying t ...

"Guidelines for inserting an image from user input into a HTML div

I am trying to dynamically add input file images to separate divs on an HTML page without using get element by class name. Each div should have a unique image associated with it instead of adding the same image to all divs with the same class. Can anyone p ...

Statement after post is not yielding any result

Below is a javascript function that I'm struggling with: function loginsubmit() { var url = "../php/loginsubmit.php"; var data = ""; ajaxRequest(url, "POST",data , true, insertNewBody); } This function is responsible for sending an ajax ...

div or paragraph element nested within a flex container

How can I make the logo text div tag, called Title, take up its content space inside the parent flexbox without wrapping? I prefer not to set the Title div to 100% or use white-space: nowrap. I simply want it to behave like a regular div where it fills it ...

How to ensure router state synchronization in a custom Vue library component with <router-link>?

I'm currently in the process of developing a reusable navigation component that utilizes vue-router <router-link> for navigation. The unique aspect of this component is that the navigation elements change styles based on active links. When I im ...

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

"Exploring Firebase features, what is the process for generating a query using UID as a reference point

I recently developed a function that assigns a UID to the database along with an item's state: changestate(item) { var postData = { state: "listed", }; var user = firebase.auth().currentUser; var uid = user.uid; var updat ...

Can a file be transferred to the server using only client-side scripting via HTML, CSS, and JavaScript?

Currently, I am looking for a way to upload a file onto my server for personal use. The downloading part is sorted out, but the challenge lies in figuring out how to upload without relying on server side scripting. I have been able to find a solution tha ...

Incorrect CSS percentage calculations detected on mobile devices

My webpage consists of three large containers, each with an alpha transparent background. While they display correctly on desktop browsers, I'm facing alignment issues on tablets (both iOS and Android) and iPhones where the percentage sum seems to be ...

Using Jquery to toggle the visibility of div elements with the same structure, but ensuring only one is

Many people have posed this question. I am attempting to create a functionality where a div can expand and collapse using a +/- button. I have 5 divs with class=="expanderContent". When the function below is triggered by a click, all 5 items expand or coll ...

Using jQuery to dynamically insert variables into CSS styles

I am attempting to use jQuery 3 to modify the CSS of a class and change the background color. My first step is converting an rgba color code (properties.color) to a hexadecimal code, which is functioning correctly. Next, I try to change the background co ...

Changing or toggling the visibility of links once the week is finished

I have a total of 4 links available, but I want to display only one link at a time, highlighting a different lunch option every week. Once all 4 weeks have passed, the first lunch menu will be shown again, starting from Monday. <div class="wrapper& ...

Is there a way to retrieve two distinct values from an object?

Is there a way to retrieve two target values from an option using useState in react/nextjs? Here is a sample of my api: const movies = [ { id: 1, name: "Fight Club" }, { id: 2, name: "Titanic" }, { ...