Vue - Function declared in methods cannot be accessed by event listener in a directive

My goal is to have my function defined in the 'methods' section execute when my element is clicked. However, the event listener only works when I use an anonymous function like

el.addEventListener('click', function() {console.log('hi'))

But when I set a function in methods, it gives me error messages like:

vue.js?3de6:634 [Vue warn]: Error in directive myDirective bind hook: "ReferenceError: sizechange is not defined"

This error occurs in the following location:

---> at /Users/soonkpaik/Downloads/Start 2/src/App.vue Here's my code:

<template>
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1 v-myDirective:sizechange='{ inisize:100, finsize:500, color:"pink", blinkcolor:"red" }'>Directives Exercise!</h1>
                <!-- Exercise -->
                <!-- Build a Custom Directive which works like v-on (Listen for Events) -->

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

<script>
    export default {
     directives:{  myDirective:{
                bind(el,binding,vnode){




                    let maincolor=binding.value.color;
                    let newcolor=binding.value.blinkcolor;        
                    let currentcolor=maincolor;

                    setInterval( ()=>{
                         currentcolor==newcolor? currentcolor=maincolor : currentcolor=newcolor

                         el.style.backgroundColor=currentcolor 
                    },500)

                     el.addEventListener('click',sizechange)






            }

        }
    },
       methods:{

        sizechange() {
            console.log('hi')

        }
    },
    }
</script>

<style>
</style>

I'm seeking help on why this isn't working properly. Thank you so much.

Answer №1

One crucial issue to consider is that the sizechange() function cannot be directly accessed within the bind hook function. To solve this, you must reference the current vnode context as shown below:

export default {
  directives: {
    myDirective: {
      bind(el, binding, vnode) {
      
        // Your logic here...
                    
        var vm = vnode.context;
        el.addEventListener('click', vm.sizechange) // This approach resolves the problem
      }    
    }
  },
  methods: {
    sizechange() {
      console.log('hi')    
    }
  },
}

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

Change the toolbar's background color to a solid white, with no gradiation

CKEDITOR.replace( 'editor_1', { toolbar: [ { ..... }, ], uiColor: 'white', }); Unfortunately, the above code does not yield the desired outcome. .cke_top{background-color: white;} It appears that the specified CSS ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

Interweaving jQuery scripts

After successfully implementing a form with jQuery, I decided to add a date picker using another jQuery code. Unfortunately, the two codes clashed and now they do not work together. Here is the initial jQuery code for the form: <!doctype html> <h ...

Utilizing Wordpress Ajax alongside additional PHP scripts

I am currently working on a simple form for my WordPress website and I seem to be encountering some issues. I am utilizing ajax to call a separate php script (named wpplugin.php) from the generic function.php script to handle all the form data. However, it ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

Ways to retrieve the previous location of a mesh

Currently, I am working on writing a shader to create the motionBlur effect in WebGL using the three.js framework. I am trying to adjust this particular tutorial for implementing WebGL: and extracting the velocity value with GPUComputeRenderer. However ...

What is the reason for function f returning the display function instead of the x value?

Hello, I have a question about this code snippet. Can you please explain why it is returning a function instead of the x value? Thank you in advance. function f() { function createClosure(x) { return function(){ return x; }; } var a ...

Leveraging jQuery to delay the processing of AJAX requests

Managing a list of 15+ ajax requests that need to be executed in a specific sequence can be challenging. Each ajax call must wait for the previous one to finish before proceeding. This issue is compounded by the fact that the callback function for each aja ...

Can I securely hand off a JavaScript callback to an FFI function that executes it in a separate thread?

I need to use a C function that takes a callback and executes it on a separate thread: void execute_in_new_thread(void (*callback)()) { // create a new thread and run `callback` in it ... } To accomplish this from JavaScript using Node-FFI, I have to ...

In the world of Sass and Vue, it is crucial to remember that the "@use" rules should always come before any other rules

When attempting to include the "sass:colors" module in my colors.scss stylesheet, I am encountering a SassError stating that "@use rules must be written before any other rules", despite it being the first line in my file. It seems like the line is being pr ...

react-router: How can a <Link> be disabled when it is already active?

Is there a way to disable a <Link> element in react-router if its URL is already active? For example, if the URL does not change when clicking on <Link>, I want to prevent any further clicks or replace the <Link> with a <span>. The ...

When does the React state update warning occur on an unmounted component?

When is the appropriate time to verify if a component has been mounted? I frequently encounter a warning in the title when using setState calls. To avoid this warning, I have started declaring a variable and initializing it to true in componentDidMount, t ...

Retrieve and display the number of items in the shopping cart directly from localStorage using React

Utilizing react along with globalContext to populate a cart page by adding items that are then stored in an array within localStorage results in the following data structure being created: 0: {id: "9", title: "Apple Watch SE 40mm (GPS) - Spa ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

JavaScript guide: Converting an array structured by tuples into a multidimensional array

I'm working with an array, X[(i,j,l)], which is indexed by 3-dimensional tuples where i and j range from 1 to n, and l ranges from 1 to "layers". This binary array consists of elements that are either 0 or 1. The array was generated as a result of so ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

What is the reason for the reconnect function not activating when manually reconnecting in Socket.IO?

After disconnecting the client from the node server using socket.disconnect(true);, I manually re-establish the connection on the client side with socket.open(). The issue arises when triggering socket.open(); the socket.on('reconnect', (attempt ...

Trim a specific portion of a string

In the event that I possess a string with the presence of x:, is there a way to exclusively eradicate that specific segment from the entire string? To illustrate: Word test description x: 28 cow dog. What steps should I take to retrieve the modified ver ...