Using VueJS to create a custom directive that takes a function as an

So here's the scenario:

HTML:

<div id="app">
  <div v-sample:callback="greet"></div>
</div>
<script>
  var app = new Vue({
    el: "#app",
    data: {
      files: [],
    },
    methods: {
      greet: function (arg) {
        alert(arg);
      },
    },
  });
</script>

JS:

Vue.directive('sample', {
  bind: function (el, binding, vnode) {
    el.addEventListener('...', function () {
      // ...
      callback.call(arg, ...);
    });
  },
});

But I'm stuck on how to properly access and evaluate the function. What is the correct syntax for doing this within a directive?

Answer №1

If you want to execute a function in Vue, utilize the binding.value property which should contain the function. It is already bound to the correct context, so simply call it (you can pass any arguments inside if needed):

Vue.directive('example', {
  bind: function (el, binding, vnode) {
    el.addEventListener('click', function () {
      binding.value()
    });
  },
});

Answer №2

Currently developing with Nuxt3 and Vue3


    // Implementing this module within defineNuxtPlugin config (client side)
    export default (vueInstance) => {
      
      // Handling click events outside of specified element
      vueInstance.directive('click-outside', {
        created(el, binding, vnode, prevVnode) {
          el.clickOutsideEvent = function (event) {
            console.log(binding.instance.close)
            if (!(el == event.target || el.contains(event.target))) {
              if(binding.instance[binding.value]) {
                binding.instance[binding.value](event)
              }
            }
          }
    
          document.body.addEventListener('click', el.clickOutsideEvent)
        },
        beforeUnmount(el, binding, vnode, prevVnode) {
          document.body.removeEventListener('click', el.clickOutsideEvent)
        }
      })
    
    }


<div v-click-outside="'close'">

</div>

Answer №3

Here is an example of how you could approach this.

<div v-customdirective:fn="params"></div>

Vue.directive('customdirective', {
    bind (el, binding,vnode) {
        let instance = vnode.context
        instance[binding.arg](binding.value)
    }
})

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 initiating a new browser window with JQuery, some data is not being transmitted

Encountering an issue with the windows.open(); method. Tech Stack: Asp.netMVC, C#, Razor Problem: jQuery When the function is triggered, it should send parameters to the Actioid and taskid controllers. However, I am facing an issue where only Actioid and ...

Transform array elements into objects with associated indices and data types

Looking for assistance in restructuring this array to meet specific formatting requirements. Struggling to achieve the desired result on my own. The parent key should be named "type" and the subparent key should have a value of "category". Any suggestions ...

While transitioning from vue2.x to vue3.x, came across an unexpected mutation of the "task" prop in the v-model module

When upgrading my project from Vue 2.x to Vue 3.0, I encountered issues with the Composition API causing the page to malfunction in Vue 3.0. The environment displayed an "Unexpected mutation of 'task' prop" error, and I'm seeking guidance on ...

What is the best way to identify when a disabled button is clicked on in JQM?

I am struggling to grasp how JQM interacts with radio buttons. My code looks like this: <fieldset data-type="horizontal" data-role="controlgroup"> <label for="radio-choice-h-2a"> Brands </label> <input name="radio-choice-h-2" ...

Unconventional JavaScript Variable Declaration

While going through some source code, I stumbled upon this peculiar variable declaration that has me a bit confused. let eventsEnabled : ?boolean = null; Can someone explain what exactly this means? You can find the source code here. ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

Combining Typescript, Javascript, and Dart in Angular 2

Can you combine all three languages - Typescript, Dart, and JavaScript - in a single Angular-2 project? For example, coding the application in Typescript, one component in Dart, and another in JS? ...

Can we stop Angular components from being destroyed during navigation?

Consider the scenario where I have two distinct Angular 2 components known as ComponentA and ComponentB. My goal is to navigate from ComponentA to ComponentB and then return to ComponentA without needing to reinitialize it. In the current setup of Angular ...

Streaming large files with Node.js can lead to significant memory consumption and potential memory errors like OOM

My current project involves using node.js to download large files (300MB) from a server and then piping the response to a file write stream. While I have a good understanding of how pipes work in Node.js, I am encountering an issue where the memory usage o ...

Is there a way to create a fading effect for background images using jQuery?

Is there a way to animate the background-image of an element with fadein and fadeout effects on hover? ...

What is the best method for users to add a div element and its contents?

As someone new to the world of web development, I am currently learning and working on a project. I have encountered an issue with creating a custom div that includes a link and user-defined text. I want the div to be generated automatically when the use ...

Loading Embedded Content with ReactJS

Currently, I am developing a one-page website with ReactJS. Each section of the site is created as individual React components, which are displayed conditionally based on the user's tab selection in the navigation bar. As part of my design, I have in ...

What is the best way to separate each quiz question and its corresponding choices into individual pages using React with Axios?

I’m a beginner in React and I’m working on creating a quiz. Currently, I have all the questions and choices displayed on the same page. However, I would like to separate each question with its choices onto different pages. When a user clicks on a cho ...

Ways to update the color of text exceeding the block boundaries: JavaScript and CSS

When dealing with background images and white text, it's common for the text to extend beyond the boundaries of the image and become invisible. I'm looking for a way to color the overflowing text in the same shade as the background image (blue). ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

The mobile button bar on iPhone is shown when scrolling or jumping up to the anchor, but it doesn't actually scroll or jump to the

My goal is to include a back-to-top button that remains fixed at the bottom of the browser window. Surprisingly, when clicked, it successfully scrolls to the top in desktop and Android browsers but fails to do so on iPhones. On an iPhone, clicking the butt ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

Creating a curved exponential data set with specific endpoints and a set number of data points

Struggling to create a function that involves math skills, I could really use some assistance. The task is to design a function that takes data points x and generates an array of size x with exponentially increasing values from 0 to 100. It would be ideal ...

Customize your header and footer for printing to display on each page

Does anyone know how to use the window.print function to print a div content with custom header and footer that will show on every page? I have been able to add a header and footer, but they only appear at the top and bottom of the print document. How can ...