How to detect a click outside of a specific element in Vue without using any external packages

I'm curious about how to hide all displayed elements when clicking outside of those elements in Vue:

<button @click="div1=true">Show div 1</button>
<div v-if="div1">DIV 1</div>

<button @click="div2=true">Show div 2</button>
<div v-if="div2">DIV 2</div>

Is there a way to hide all divs except div 1 when I click on div 1 or hide all divs when clicking on a random section of the page? How is this handled in Vuetify?

Answer №1

To utilize Vue in a different manner, you can access the DOM element of the current component using this.$el. This allows you to modify this.$el and replace it with any other HTMLElement.

<div class="modal" @click="handleClick">
  <div class="modal-dialog">
    <div class="modal-content">
    ...
    </div>
</div>

The method for handling this should be structured as follows:

handleClick(e: Event): void {
  if (e.target instanceof HTMLElement && !this.$el.contains(e.target)) {
    this.$emit("hide"); //trigger only when clicking outside
  }
}

Answer №3

In order for the Home component to be aware of any clicks outside of the Nav component, I implemented a specific process. This was made possible by having the nav element nested within the Home Component.

The template for my Home component looks like this:

<div>
 <nav-bar ref="nav"></nav-bar>
  <div @click="useHideNavMethod()">

By using ref="nav", I am able to access and utilize methods from the Nav component in the Home component. This setup allows me to invoke the hideNav() method (which is located in the Nav component). I intentionally positioned the nav outside of the div with the click event, so that clicking anywhere other than the Nav would trigger the useHideNavMethod() function.

In the template of my Nav component, I have:

<nav id="nav"> 

This is what is referenced when I make use of ref="nav".

Within the hideNav() method, I have included

this.styleNavLi.display = 'none';
in order to hide the navigation bar.

To call this method from the Home component, all I need to do is:

useHideNavMethod() {
 this.$refs.nav.hideNav();
}

Answer №4

To switch between views, use div1 = !div1, Or for a one-time show, use div1 = true.

<template>
  <div>
    {{ div1 }}
    <button @click="div1 = !div1">Show div 1</button>
    <div v-if="div1">DIV 1</div>

    {{ div2 }}
    <button @click="div2 = !div2">Show div 2</button>
    <div v-if="div2">DIV 2</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      div1: true, // set your preferred default value
      div2: false,
    };
  },
};
</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

I am looking to utilize the JavaScript YouTube API to seamlessly upload a video from my website directly to YouTube

Currently facing an issue with uploading a video from my webpage to YouTube using the JavaScript YouTube API. The error code I'm receiving is "User authentication required" (401). Can anyone provide me with a demonstration example in JavaScript that s ...

How can array data be organized by date in an Ajax response?

i have an array with the following data [{ date: "January 2019", sum: 20, name: "Persada", },{ date: "Februay 2019", sum: 21, name: "Persada", },{ date: "April 2019", sum: 22, name: "Persada", },{ date: "January 2019", ...

Extracting an extension from a file name containing special characters in JavaScript: A step-by-step guide

I am attempting to extract the file extension from a filename. The filename may incorporate special characters such as "#, @, ., _, (), etc. For example: var file1 = "fake.der" var file2 = "fake.1.der" var file3 = "fake_test.3.der" In the scenarios above ...

Discover the method of utilizing my current location to determine the distance between two points by inputting their latitude and longitude

I'm currently working on customizing my REST API to only retrieve items that fall within a specific radius. I have successfully written the code to calculate the distance between two points and filter out items outside the desired range. However, my c ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

Validation in Laravel appears to be ineffective when managing schedules

I have a table that contains schedules for each subject. I want to ensure that every schedule is unique and not duplicated. The table includes columns for room, teacher, time, day, and checker who verifies the schedule. It's essential that there are n ...

How can I determine the width of a div element and then set a limit for the mySQL query based on the number

My goal was to dynamically display a certain number of images based on the width of a div element that increases automatically according to screen size. <li><img class='1'><img class='1'><img class='1'> ...

Deciphering Complex JSON Data Structures Using JavaScript

UPDATED OUTPUT I successfully utilized the request module, which now delivers verified standard JSON output. Check out the updated result below: const respBody = { "items" : [ { "id" : "T0lDX0J1aWxkX0FydGlmYWN0czpmODk4YjM5MDNjYjk5NzU5NjgzNTk3ZWRj ...

What is the best way to extract the variable inside a script tag as a JSON value?

Hey, I need help figuring out how to convert a JavaScript variable into a JSON value using Python with the help of libraries like BeautifulSoup and requests. I attempted to solve this issue by following a similar topic on Stack Overflow, but unfortunately ...

What is the best way to showcase a non-image file that is stored in MongoDB (using GridFS) on a webpage?

I have a project where users can upload documents (not images) that are stored in MongoDB using GridFS. My question is, is there a way to display these documents on the site for viewing instead of just downloading them? I've tried using the createRead ...

Mechanism for creating variables in Angular through factory services

While delving into the world of angular1, I encountered services and factories. Using the .factory() method, I passed in a string that represented the desired service name. Surprisingly, I found myself able to reference a variable matching this string wi ...

Finding unique values by mapping and returning them without any duplicates

Currently, I'm working on a mapping task and facing an issue. In my code snippet, I attempted to eliminate duplicate values by using <h3 key={i}>{_.uniq(person.name)}</h3> from lodash library. However, the output still displays duplicate v ...

Is there a way to determine the number of syllables in text as it is being typed?

Working on a React-based web app, I am trying to determine the number of syllables in a textarea as the user types. Encountering errors like "cannot find length of a null" at every turn. Right now, all I want is to utilize console.log() for troubleshooti ...

Retrieving a specific item using a key in Vue.js

In my Vue template, I have the following data: 0: { id:1, name:test1} 1: { id:2, name:test2} 2: { id:3, name:test3} While the loop <div v-for="(product, index) in products" :key="product.id"> works perfectly, I am wondering how I ...

The Scrollbottom functionality fails to operate in Firefox, Chrome, and Safari browsers

I have implemented a scrollbottom feature using JQuery (1.3.2/jquery.min.js) to automatically scroll to a specific div at the bottom of the page. While this functionality works perfectly in IE 8 & 9, it does not work in Firefox, Chrome, or Safari. The ...

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...

Ways to have Express backend redirect you following a successful submission of a request via the Fetch API from the frontend?

Behold the following code snippet which illustrates the typical backend sign-in logic. If the user's credentials are correct, they will be redirected to the admin panel: import Express from "express"; import { Controller, Post, Body as Reque ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

Guide on linking an HTML table to an Excel spreadsheet through PHP

In a project I'm working on, there is a table with columns for name, attendance status, date, and times in and out. I am looking for ways to connect this system to an Excel spreadsheet acting as the database using PHP. I have attempted to learn from ...

Adjust the opacity of a div as you scroll using jQuery

Check out my code snippet: http://jsfiddle.net/spadez/Fq5K4/ I am looking to create a cool effect where the image in the top section gradually turns black as the user continues scrolling down the page, until it is completely black. This example showcases ...