How can I utilize target.event to close the dropdown in Vuejs when clicked outside of it?

const app = new Vue({
  el: "#app",
  name: 'aselect',
  data: {
    value: 'Select a Fruit',
    list: ["Orange", "Apple", "Kiwi", "Lemon", "Pineapple"],
    visible: false
  },
  methods: {
    toggle() {
      this.visible = !this.visible;
    },
    select(option) {
      this.value = option;
    }
  }
})
<div id="app">
  <h1>Custom Select Dropdown</h1>

  <div class="aselect" :data-value="value" :data-list="list">
    <div class="selector" @click="toggle()">
      <div class="label">
        <span>{{ value }}</span>
      </div>
      <div class="arrow" :class="{ expanded : visible }"></div>
      <div :class="{ hidden : !visible, visible }">
        <ul>
          <li :class="{ current : item === value }" v-for="item in list" @click="select(item)">{{ item }}</li>
        </ul>
      </div>
    </div>
  </div>
</div>

I found the solution I was looking for on https://www.npmjs.com/package/vue-click-outside

You can check out my implementation on CodePen here https://codepen.io/santoshch/pen/gOmvvmN. In this dropdown example, I faced an issue where the dropdown list wouldn't close after toggling down.

To fix this issue, I explored options within Vue.js and came across a useful npm package called vue-click-outside. I attempted to incorporate this event listener into my code but needed guidance on how to proceed further with its usage.

Answer №1

Here is a solution to the issue you're facing. Follow the steps below: First, make sure to add the box class to every element within the box that triggers the dropdown effect.

<div id="app">
  <h1>Custom Select Dropdown</h1>;

  <div class="aselect" :data-value="value" :data-list="list">
        <div class="selector box" @click="toggle()">
            <div class="label box">
                    <span class="box">{{ value }}</span>
            </div>
            <div class="arrow box" :class="{ expanded : visible }"></div>
            <div :class="{ hidden : !visible, visible }">
                <ul>
                    <li :class="{ current : item === value }" v-for="item in list" @click="select(item)">{{ item }}</li>
                </ul>
            </div>
        </div>
    </div>
</div>

Next, ensure to add a click listener to the window in Vue.js.

    const app = new Vue({
    el: "#app",
        name: 'aselect',
        data: {
            value: 'Select a Fruit',
            list: ["Orange","Apple","Kiwi", "Lemon", "Pineapple"],
            visible: false
        },
        methods: {
            toggle() {
                this.visible = !this.visible;
            },
            select(option) {
                this.value = option;
            },
            handleClick(e){
               const classname = e.target.className;
               if(this.visible && !classname.includes("box")){
                  this.visible = false;
               }
            }
        },
    created () {
      window.addEventListener('click', this.handleClick);
    },
    destroyed () {
      window.removeEventListener('click', this.handleClick);
    },
})

You can also check out this pen for reference: https://codepen.io/salim-hosen/pen/xxqYYMQ

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

How can eslint be used to enforce a particular named export?

Is there a way to use eslint to make it mandatory for JavaScript/TypeScript files to have a named export of a specific name? For instance, in the src/pages folder, I want all files to necessitate an export named config: Example of incorrect usage src/page ...

Having difficulty toggling checkboxes within a grid using the select all feature

In order to toggle checkboxes for a specific column within a grid, I encountered an issue within the JS "onUPCSelectAll" function with the eval statement displaying the following error message: JS runtime error: Object doesn't support property or meth ...

What is the best way to display the ID value as a variable in a bootstrap modal dialog?

I originally thought figuring this out would be a breeze, but it's proving to be quite the challenge. After scouring for solutions without success, I find myself stuck. There's a list of dynamically generated buttons with unique id values that I ...

Arrange objects in an array by the date field using Meteor

I have updated my user collection in my Meteor app with an array of objects named contacts. This is how it looks now: { "_id" : "p6c4cSTb3cHWaJqpG", "createdAt" : ISODate("2016-05-11T11:30:11.820Z"), "services" : { ..... }, ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

Selecting the textarea element within a form using jQuery

Here is a code snippet that I've been working with: <!DOCTYPE html> <html> <head> <meta http-equiv='Content-Type' content='text/html;charset=utf-8' /> <script type='text/javascript' sr ...

JavaScript code that uses jQuery does not function properly on an HTML form

Hello everyone, I am having trouble with some JavaScript code. Here is what I have: $(document).ready(function(){ $(".replyLink").click(function(){ $("#form-to-"+this.id).html(htmlForm()).toggle(500); return false; }); function htmlForm(){ var htm ...

Finding descendants using a jQuery object that has been saved

As I cycle through some unordered lists, I aim to retrieve all of the descendants using the saved jquery-wrapped selectors. Below is the HTML snippet: <ul> <li><a href="#">item 1</a></li> <li><a href="#"> ...

Extracting specific data from csv or JSON files using Node.js

In my attempt to extract specific information from a csv file with multiple rows, I am using papa/babyparse to convert the data into JSON format. However, I am facing challenges in displaying/extracing particular values or columns from a designated row. v ...

sending a selection of JSON string values to a jQuery function

I have a JSON string that contains different items, but I am only interested in the 'locked' array and would like to pass it to a jQuery function. The JSON string was generated using json_encode from PHP. {"ignored":[],"status":{"message":"succe ...

Utilizing Quill Text Editor in Vue.js: A Step-by-Step Guide

I developed a custom Quill text editor component in Vue, showcasing the code below: <template> <div ref="editor"></div> </template> <script> import Quill from 'quill'; import 'quill/dist/quill.core.c ...

What is the best method for testing an Angular service that has dependencies in Jasmine?

My service implementation is structured as follows: angular.module('app').service('MyService' , function (dependency1, dependency2, dependency3 ...) { function funcToTest() { // Do something } } I am wondering how I ca ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

Is it possible to nest a React component within a state?

Is it permissible to use any of the three options below, but I can't find recent official information regarding this? constructor(props) { this.state = { item: <SomeItem />, item1: () => <SomeItem />, item2: Some ...

Setting the position of a tooltip relative to an element using CSS/JS

I'm struggling to make something work and would appreciate your help. I have a nested list of items that includes simple hrefs as well as links that should trigger a copy-to-clipboard function and display a success message in a span element afterwards ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...

Looking for assistance with finding a specific value in Firestore?

As I venture into using firestore for the first time, I'm in the process of creating a registration page with vue. One crucial step before adding a new user to the database is to validate if the provided username already exists. If it does not exist, ...

Jquery trigger causing href links to malfunction

Here is a JavaScript example: var sampleFunction = function(){ return { initialize : function(data) { this.sendRequest({ action : 'login' }); }, loginAction : function() { ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

When modifying a form that contains a FileField, the file will be automatically

In my ModelForm, I have fields that are generated dynamically. While everything works well, I have an issue with editing. The input[type=file] field loses its file when editing and instead, it displays a link like <a href="/path/to/file"> with the te ...