Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly.

Here is my code snippet:

import { DirectiveOptions } from 'vue';
interface WfmCarriageDirectiveModel {
    onFocusDown(): void;
    onKeyDown(event: Event): void;
    resetInput(): void;
    changeOrientation(event: Event): void;
    getNumber(keyCode: number): void;
    getDeflection(keyCode: number): void;
}
const ORIENTATION_VERT = 'vert';
const ORIENTATION_HOR = 'hor';

class WfmCarriageDirective implements DirectiveOptions, WfmCarriageDirectiveModel {
    // The rest of the class definition...
}

export default WfmCarriageDirective;

After defining the directive, I added it in Main.ts:

import WfmCarriageDirective from '@/directives/wfmCarriageDirective';
Vue.directive('wfm-carriage', new WfmCarriageDirective());

Below is a snippet of my template where I am using the directive:

<div v-for="(plan, planKey) in planMap[employee.id]"
       :class="[
       `employees-cell ${plan.idEmployee}-${planKey}`,
       {
        'weekend': plan.isWeekend || plan.isHoliday,
       'select': isSelectedCell(plan),
       'vert': isSelectedCell(plan) && isVerticalOrientation(),
       'hor': isSelectedCell(plan) && !isVerticalOrientation(),
       'not-editable': !isEditable(plan)
       }]"
       @mousedown="selectCell(plan, roleId)"
       tabindex="1"
       v-wfm-carriage="{
       plan: {value: plan, key: planKey},
       rolesMap: rolesMap[roleId],
       shifts: shiftsMap.byCode.shifts,
       orientationCarriage,
       onChangeOrientation,
       controlAndInput
       }"
>

However, during component initialization, I encounter an error saying "Cannot set property 'orientationCarriage' of undefined" and "Error in directive wfm-carriage bind hook: "TypeError: Cannot set property 'orientationCarriage' of undefined."

Can anyone guide me on how to access 'this' in the bind hook?

Answer â„–1

A bit delayed, however, here's a suggestion that might be useful: Instead of using bind, consider using inserted.

For more information, you can refer to the official documentation

Directive Hook Functions When defining a directive object, there are several optional hook functions available:

  • bind: executed once when the directive is initially bound to the element. Use this for any setup work needed only once.
  • inserted: triggered when the bound element has been inserted into its parent node (parent presence guaranteed, not necessarily in-document).
  • update: called after the containing component’s VNode updates but potentially before its children do. The value of the directive may or may not have changed; compare current and old values to avoid unnecessary updates (detailed in hook arguments below).

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

Tips for creating an array within an AngularJS Service and effectively sharing it across two controllers

I have two controllers, FirstController and SecondController, along with a service defined as follows: app.factory('Data', function(){ return []; }); In both controllers, I am utilizing the service in this manner: app.controller("FirstCont ...

Facing issues with building Angular 7 and Ionic 4 - getting error message "TypeError: Cannot read properties of undefined (reading 'kind')"

I need assistance with a problem I am encountering while building my Angular 7 & Ionic 4 application... When I run the ng build --prod command, I encounter the following error: ERROR in ./node_modules/ionic4-auto-complete/fesm5/ionic4-auto-complete.js ...

Including onMouseUp and onMouseDown events within a JavaScript function

I am experiencing an issue with a div that contains an input image with the ID of "Area-Light". I am attempting to pass the ID of the input image to a function. Although event handlers can be directly added inside the input tag, I prefer to do it within ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

jQuery interprets every PHP response as having a status of 0

I've been working on a way for javascript to verify the existence of a user in a MySQL database. My method involves using jQuery to send the user details to a PHP script that will then check the database. The data is successfully sent to the PHP scr ...

Switch out a visual element for Dropzone.js

During my recent project, I utilized Dropzone.js for image uploads. However, I am now interested in transforming the dropzone area into an actual image. For instance, if there is a "featured image" attached to an article, users should be able to drag and ...

In TypeScript, there is a mismatch between the function return type

I am new to TypeScript and trying to follow its recommendations, but I am having trouble understanding this particular issue. https://i.stack.imgur.com/fYQmQ.png After reading the definition of type EffectCallback, which is a function returning void, I t ...

Guide to testing Higher Order Components with React Testing Library

I've created a higher-order component (HOC) that adds props to a component for handling network requests and passing down data as props. Below is a simplified version of the HOC: export const withTags = (Component) => { class WithTags extends Pur ...

Unveiling the secrets of using VueJS modifiers in PUG

Can you provide guidance on using modifiers with Pug? I attempted the following: my-component(:options.sync="addresses") my-component(':options.sync'="addresses") Both resulted in a syntax error, unexpected token. my-component(:options="addr ...

What is the best way to adjust the vertical margin in a vis.js timeline?

The vis.js timeline sets a margin of 5px in each row using inline styles that are controlled programmatically by the library. The height, top position, and transform of each item within the row are specified by the library as well. Attempting to manually ...

Attempting to create a promise for a dropdown menu in React-Select

I am facing an issue here: type Person = { value: string; label: string; }; Furthermore, I have a promise-containing code block that fetches data from an API and transforms it into the appropriate array type for a React component. My intention is to r ...

My Node.Js app refuses to run using my computer's IP address, yet works perfectly with localhost

My Node.js application is set up to listen on port 5050 of my machine: Visiting http://localhost:5050/myapp loads the app successfully. I am using the Express framework, so my listening framework looks like this: var server = app.listen(5050, '0.0.0 ...

Trouble with Ruby on Rails jQuery interactions when using the tokenInput gem

Currently, I am developing a rails app and attempting to incorporate this gem for a text field https://github.com/exAspArk/rails-jquery-tokeninput Despite having the gem correctly installed and included in my _form.html.erb file, I keep encountering the ...

Utilizing React Typescript to Dynamically Restrict Props Configuration Based on Data

I am new to TypeScript and I have a question regarding passing dynamic data to a React component while restricting props setting. I came across a simple component with the constraint of "RandomNumberProps", where the component can only accept either "isPo ...

A guide on linking v-for values to HTML attributes in Vue

I'm attempting to assign the values I receive from a v-for loop to attributes within the same tag, but so far without success. Here is the code snippet in question: <label v-for="hashtag in hashtags" v-bind:title=`You can filter wit ...

Can someone please provide guidance on how to reset the value within a Q Select component in Quasar Framework

Currently, I am in the process of developing a Vue.js application using the innovative Quasar Framework. One challenge I face is resetting a q-form within my project. If you're interested in learning more about Quasar forms, here's a helpful re ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

How to apply class binding within a v-for loop in Vue.js

When using Vuejs3, I am currently iterating through an array of objects: <div v-for="ligne in lignes" :key="ligne.id" :class="{ 'border-b-2':isSelected }" :id="`ligne_${ligne.id}`" > ...

An issue with TypeORM syntax causing errors within a NestJS migration file

I recently encountered an issue while setting up PostgreSQL with NestJS and TypeORM on Heroku. Despite successfully running a migration, my application kept crashing. I attempted various troubleshooting methods by scouring through blogs, GitHub issues, and ...