Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet:

export default {
    name: "ProSelect",
    data() { return {
        isActive: false,
    }},
    methods: {
        select(event) {
            console.log('ID :' + event.currentTarget.id);
        }
    }
}
<div
    v-if="isActive"
    class="absolute shadow bg-white top-100 z-40 w-full lef-0 rounded max-h-select overflow-y-auto">
    <div class="flex flex-col w-full">

        <div
            id="foo"
            @click="select($event)"
            class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
            <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                <div class="w-full items-center flex">
                    <div class="mx-2 -mt-1">
                        Jack jhon
                    </div>
                </div>
            </div>
        </div>

        <div
            id="foo2"
            v-on:click="select($event)"
            class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
            <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                <div class="w-full items-center flex">
                    <div class="mx-2 -mt-1">
                        Jack jhon 2
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</div>

If I change the isActive variable to true during rendering, the click event works fine.

I came across a workaround where using @mousedown.prevent instead of @click makes it work.

Answer №1

It seems like the parent div will be removed from the DOM if the code you posted has a false v-if. You can set isActive to true during mounting.

Here is a Working Demo :

new Vue({
      el: '#app',
      data() {
          return {
              isActive: false,
          }
      },
      methods: {
        select(event) {
          console.log('ID :' + event.currentTarget.id);
        }
      },
      mounted() {
        this.isActive = true;
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
      v-if="isActive"
      class="absolute shadow bg-white top-100 z-40 w-full lef-0 rounded max-h-select overflow-y-auto">
      <div class="flex flex-col w-full">

          <div
              id="foo"
              @click="select($event)"
              class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
              <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                  <div class="w-full items-center flex">
                      <div class="mx-2 -mt-1">
                          Jack jhon
                      </div>
                  </div>
              </div>
          </div>

          <div
              id="foo2"
              v-on:click="select($event)"
              class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
              <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                  <div class="w-full items-center flex">
                      <div class="mx-2 -mt-1">
                          Jack jhon 2
                      </div>
                  </div>
              </div>
          </div>
      </div>
  </div>
</div>

Answer №2

this is the complete template code

<template>
    <div>
        <div class="flex flex-col items-center">
            <div class="w-full flex flex-col items-center">
                <div class="w-full">
                    <div class="flex flex-col items-center relative">
                        <div class="w-full">
                            <div class="flex">
                                <div class="flex flex-auto flex-wrap"></div>
                                <input
                                    class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:rounded-none focus:rounded-lg focus:border-b-0 focus:bg-white focus:border-indigo-500 border-transparent focus:border-transparent focus:ring-0"
                                    type="text"
                                    v-model="selected"
                                    :name="name"
                                    @focusin="isActive = !isActive"
                                    @focusout="isActive = !isActive"
                                    placeholder="Search by position">
                            </div>
                        </div>
                        <div
                            v-if="isActive"
                            class="absolute shadow bg-white top-100 z-40 w-full left-0 rounded max-h-select overflow-y-auto">
                            <div class="flex flex-col w-full">

                             <div
                                id="foo"
                                @click="select($event)"
                                class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
                                <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                                    <div class="w-full items-center flex">
                                        <div class="mx-2 -mt-1">
                                            Jack John
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <div
                                id="foo2"
                                v-on:click="select($event)"
                                class="cursor-pointer w-full border-gray-100 rounded-t border-b hover:bg-teal-100 hover:bg-gray-100 hover:border-indigo-500">
                                <div class="flex w-full items-center p-2 pl-2 border-transparent border-l-2 relative hover:border-teal-100">
                                    <div class="w-full items-center flex">
                                        <div class="mx-2 -mt-1">
                                            Jack John 2
                                        </div>
                                    </div>
                                </div>
                            </div>




                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...

Eliminating redundant JSON records upon fetching fresh data

I have a list containing duplicate entries: var myList = [ { "id": 1, name:"John Doe", age:30 }, { "id": 2, name:"Jane Smith", age:25 }, { "id": 3, name:"John Doe", age:30 }, { &qu ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Maintaining scope integrity in an Angular application with components, including a dialog that utilizes a custom directive

I'm struggling with passing scope to a template rendered from a directive. It seems like it should be simple, but I can't seem to get it to work properly. Here is a simplified version of my HTML: <div ng-app="myApp"> <md-content> ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

In AngularJS, enhance pagination loading by appending a $resource queried array to the end of another

I'm currently working on implementing a loading feature for my Angular application. The goal is to preload page 3 when a user navigates to page 2. Utilizing $resource, I'm querying the Posts resource using Post.query(). By calling Post.query({pa ...

Looking to organize my divs by data attributes when clicked - how can I achieve this with javascript?

I am looking to implement a dropdown sorting functionality for multiple divs based on different data attributes such as price and popularity. The specific divs are labeled as "element-1" and are contained within the "board-container". var divList = $(". ...

The error `Error occurred when rendering: Users' data cannot be mapped` indicates a problem with the rendering process

Utilizing useSWR for data retrieval from an endpoint and attempting to display all returned data, I encounter the following error: unCaught (in promise) fetchedUsers.map is not a function uncaught TypeError: fetchedUsers.map is not a function The provided ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Issue with Vue.js Checkbox functionality in Firefox, functioning smoothly in Chrome and IE

I have implemented a checkbox feature in my project. <template v-for="(item,index) in items"> <div> <input type="checkbox" v-model="item.checked" @click="selectionCheckboxClicked(index,item.checked)" ...

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

Identify any missing periods and combine the years into a single range

I am working on restructuring year ranges with gaps and consolidating them. For example, converting [{start: 2002, end: 2020}, {start: 2020, end: null}] to {start: 2002, end: null} or [{2002, 2004},{2006, 2008}, {2008, null}] to [{2002-2004}, {2006-null}]. ...

Troubleshooting: Dealing with the issue of the inability to locate a module using the "@" path during VueJS unit testing

I encountered an issue with a component: <template> <span :class="lightClassName"> <i class="fas fa-circle markIcon" /> </span> </template> <script> import { EnumAttendanceStatuses } from "@/enums"; export ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Tips for resolving an Angular 504 Error Response originating from the backend layer

I am currently facing an issue with my setup where I have an Angular application running on localhost (http) and a Spring Boot application running on localhost (https). Despite configuring the proxy in Angular to access the Spring Boot APIs, I keep receivi ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

Eliminate screen flickering during initial page load

I've been developing a static website using NuxtJS where users can choose between dark mode and default CSS media query selectors. Here is the code snippet for achieving this: <template> <div class="container"> <vertical-nav /> ...

Are there alternative methods for utilizing ionicons without needing the <script> tag?

In our workplace, the designer opted to incorporate ionicons but the documentation only provides instructions on how to use them without Ionic: Insert the following <script> at the end of your page, right before the closing </body> tag, to ac ...

Receiving a blank request payload despite implementing a body parsing middleware

I am currently working on setting up a login system, and I have a form that sends a post request to my webpack dev server. This server then proxies the request to my actual server. Here is the function responsible for handling the form submission and send ...