Tips for ensuring that the logic within a custom vue directive is only executed when the corresponding element is clicked

I am currently facing an issue where the directive I attach to an element is being executed when the page loads, but I want it to run only when that element is clicked. How can I achieve this functionality?

  directives: {
            'new-dir': {
                bind(el, binding, vnode) {
                    el.style.cursor = "pointer";
                    console.log(vnode);
                    if(vnode.tag == 'div'){
                                ...something       }
                    else if(vnode.tag == 'a') {
                      console.log("its a link and clicked");
                      if(vnode.data.attrs.target == "_blank"){
                        console.log("external link");
                      } else{
                        console.log("internal link");
                      }
                    } else if(vnode.tag == 'input') {
                       console.log("its an input ");
                       console.log("type = " + vnode.data.attrs.type)
                       console.log("placeholder = " + vnode.data.attrs.placeholder);
                    }
                }
            },
  }

Answer №1

Bindings in directives are essential as they determine when the directive code should execute.

To implement specific logic for a click event, it is necessary to define a click handler.

directives: {
  "custom-dir": {
    bind: el => {
      el.style.cursor = "pointer"
    },
    inserted: (el, binding, vnode) => {
      // save reference to click handler on element
      // allows for removal later
      el.customDirClickHandler = e => {
        console.log(vnode);
        if (vnode.tag == 'div') {
          // perform action for div tag
        }
        if (vnode.tag == 'a') {
          console.log("link clicked");
          if (vnode.data.attrs.target == "_blank") {
            console.log("external link");
          } else {
            console.log("internal link");
          }
        }
        if (vnode.tag == 'input') {
          console.log("input clicked");
          console.log("type = " + vnode.data.attrs.type)
          console.log("placeholder = " + vnode.data.attrs.placeholder);
        }
      }

      // register the click handler
      el.addEventListener("click", el.customDirClickHandler)
    },
    unbind: el => {
      // remove the click handler
      el.removeEventListener("click", el.customDirClickHandler)
    }
  }
}

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

Performing an AJAX request from a secure HTTPS page to an insecure HTTP URL

Currently, I am facing a scenario where I must execute an AJAX request from an HTTPS webpage to a non-secure page on a different domain. Our CORS policy was functioning correctly prior to switching to HTTPS on our site. Are there any solutions to resolve ...

The concept of a callback function is not applicable within the context of MongoDB in Node.js

I am encountering an issue while validating the existence of an email or username in my MongoDB users collection within Node.js using my User Model. Whenever I attempt to perform this validation, I receive an error stating callback is not a function. This ...

Having issues with JavaScript/jQuery onclick functionality

My attempts to test a script using the test.html document are failing. I can't figure out why nothing is happening. The Script is contained within script tags and wrapped with style tags. Why isn't it working? Here is the code <!DOCTYPE html& ...

Ways to Retrieve the Value of an Object

Here is some sample data: { "id": 1, "title": "Title one", "category_data": { "2": "Team", "7": "Queries" } }, A function is used to remove duplicate categories from the data: remove_category_duplicates: function () ...

Using AngularJS to apply a class only if an element exists

I'm attempting to assign a class to li elements if they contain content. Check out my code: <li ng-repeat="answer in answers" ng-class="{'textleft': textleft}"> <p class="left" ng-bind="maintext"></p> <p class= ...

The second click does not impact the props received by the child component

I created a basic app with a link to the code. The child component receives props like this: props: ['isActive'], and then it changes its value to display a modal window: data: function() { return { isActive: this.isActive // value from pr ...

The results of the Mongoose aggregation $lookup operation are coming back as an empty array in the 'as' field

Suppose we have two datasets: Order and Seller for a platform similar to Ebay where customers can purchase items from individual sellers. Every Order includes a seller field that indicates the ID of the shop owner. const orderSchema = new mongoose.Schema( ...

Assistance requested with Javascript for an HTML dropdown menu

My question involves utilizing two HTML drop down menus. <select> <option value="">Please Select</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option ...

Display the JSON boolean value on the webpage using Ajax and Jquery

After using Ajax with a GET request to consume a REST web service, I now have the results displayed in my console. Here are some images related to the REST API I am consuming: https://i.sstatic.net/Nv7F7.png https://i.sstatic.net/OXhUg.png However, whe ...

Utilizing jQuery's 'contains' method to select an element and apply a CSS class

My goal is to create a dynamic navigation system. Specifically, I want to switch between using a Bootstrap list group and nav pills based on the screen size. The challenge I'm facing is capturing the current active element and adding the 'active& ...

Exploring Quasar app environment variables

I am having trouble accessing an environment variable. I have tried creating a .env file and setting the variable as VUE_APP_TOKEN: 11token22, but when I try to log it with console.log, it returns undefined. Next, I attempted to set the environment variab ...

Leveraging jQuery data to handle RESTful requests

I am currently working on filtering the request response based on the status code that is returned. I have figured out how to retrieve the status code using the "complete" statement, but I am unsure about how to access the data handler. My goal is to inc ...

Take action upon being added to a collection or being observed

Consider the following scenario: I have an array called "x" and an Observable created from this array (arrObs). There is a button on the page, and when a user clicks on it, a random number is added to the array. The goal is to display the newly added value ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Incorporate a Web Worker into your webpack library for enhanced performance

I am facing an issue while attempting to include a web worker in my custom npm package. [App] -> [my npm package -> load worker] Within the npm package, I am utilizing worker-loader to import the worker file: import Worker from 'worker-loader! ...

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

Transforming the Blade user profile into a sleek Vue interface for the Laravel-Vue project

They have requested me to convert all pages from blade to vuejs. I have begun the process with the user profile (Profile.vue), but I am unsure about how to execute PUT requests using Axios in this case. Can someone provide guidance on creating the code for ...

Converting a serialized PHP array using JavaScript

I am working with a PHP array: <?php information = array ( 'name' => 'John', 'surname' => 'Doe' ); ?> After serializing this array in PHP, I have inserted it into an input's ...

Real-time page updates and on-the-fly event monitoring

As I tackle a specific logical challenge, I find myself struggling a bit. Here is the issue at hand: When sending a PUT request from within a controller using certain factory methods, my aim is to update the data without triggering a page refresh. For exa ...

Sending files correctly using Node.js

Here is a simple middleware to consider: (req, res, next) => { const stream = fs.createReadStream(req.filePath) await new Promise((resolve, reject) => stream .on('error', reject) .on('end', resolve) .pipe(res ...