Implementing Vue directives in separate files and importing them into components: A step-by-step guide

For a project using Vuelidate, I have set up a timeout for validation when a user types something. While I achieved success using mixins, I wanted to adhere to good coding practices by creating a Vue directive without globally registering it, and utilizing it in specific components.

To achieve this, I created an external file named directives/delayTouch.js. Initially, I attempted to export only a const using export const, but Vue required me to use export default instead.

const delayTouch = {
  inserted ($v) {
    const touchMap = new WeakMap()

    $v.$reset()
    if (touchMap.has($v)) {
      clearTimeout(touchMap.get($v))
    }

    touchMap.set($v, setTimeout($v.$touch, 1000))
  }
}

export default delayTouch

Subsequently, I imported this directive into my component:

<template>
  <TextField
    v-delay-touch="$v.data.name"
    :v="$v.data.name"
    v-model.trim="$v.data.name.$model"
    id="name"
    label="Nome da campanha"
  />
</template>
<script>
import delayTouch from '@/directives/delayTouch'
    
export default {
  directives: { delayTouch }
}
</script>

Despite correctly passing the HTML in the param ($v), I am encountering the error message $v.reset is not a function. What could be the reason behind this issue?

Answer №1

When using directive hooks, you will receive 4 arguments as follows:

  • el, binding, vnode, and oldVnode

It's important to note that the first argument in the inserted hook refers to the HTML element itself, not the $v object. To access a component property within the directive, you can use the directive's vnode argument to retrieve the component's context:

inserted(el, binding, vnode) {
  const $v = vnode.context.$v;
  ...
}

Whenever you need to interact with the element in the directive, remember to utilize the el parameter.

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

"Utilizing jQuery to apply a class based on the attributes of CSS

Is there a way in jQuery (or plain JS) to create a condition based on whether a div has a specific CSS attribute? For instance, I need jQuery to apply position:fixed to an element's CSS when another element has display:none, but switch back to positi ...

What could be causing the lack of color change in my boxes even after confirming the prompt?

function changeColor() { if (confirm("Press a button!") == true) { if(this.style.backgroundColor == "white") this.style.backgroundColor = "yellow"; else if(this.style.backgroundColor == "yellow") this.style.backgroundColor = "red"; else i ...

Conundrum encountered: SIGTRAP causing Electron failure to initialize

Exploring Electron for creating desktop applications has been my recent endeavor. However, I encountered this pesky error: /home/me/dev/my-electron-app-2/node_modules/electron/dist/electron exited with signal SIGTRAP Since the path leads to a binary file, ...

Waypoints unable to display - Google Maps API issue

I am attempting to retrieve the waypoints from an AXIOS call and utilize the response to populate the city into a waypts array. Unfortunately, when I try to include the waypoints in the route, the map only shows the route from the starting point to the des ...

Trigger the next button click event using jQuery

Is it possible to implement a slideshow on my website where clicking a button displays the relevant slide? My goal is to incorporate a timer that will automatically click the next button after 3 seconds, enabling the slideshow to transition automatically. ...

Is it better to manually input a list of select options in the user interface or retrieve them dynamically from the database in case of future changes?

Imagine designing a user interface that allows users to choose their favorite Pokemon from options like Bulbasaur, Squirtle, and Charmander. Within the database, there is a lookup table containing all possible choices: pokemon --- id name 1 Bulbasaur 2 ...

Updating Mapped Components with Selected State

One of the components in my project is a mapped component that dynamically displays API data. Each card displayed by this component receives unique props, resulting in cards that look different from one another. An example can be seen below. View Example ...

Utilizing a library across various files in Node.js

I am looking to integrate Winston for logging in my nodejs express project. Within my main file ( server.js ) I currently have the following code snippet: const winston = require('winston'); winston.level = process.env.LOG_LEVEL winston.log(&ap ...

Extracting user input from an iframe and transferring it to another frame in HTML format

Can someone advise me on how to extract values from iframe1 and transmit them to iframe2 as HTML? I am open to either JavaScript or jQuery - no preference. As a beginner in javascript, I stumbled upon some code that seems relevant. <!DOCTYPE html> ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

How can you make the table rows in jQuery scroll automatically while keeping the table header fixed in

Many solutions exist for making the header fixed and the table scrollable using code samples or plugins. However, my specific goal is to have the table data rows scroll automatically once they are loaded while keeping the header fixed in place. Is there a ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...

Is it possible to operate a jQuery mobile web application while disconnected?

Recently, I've been experimenting with the idea of creating a web application using jQuery Mobile that involves utilizing forms such as checkboxes, text fields, and combo boxes. The tasks associated with this app are quite simple, but they require dat ...

Automated playback of integrated Twitter video

Is there a way to make embedded Twitter videos autoplay? The code generates an iframe which is preventing me from using some JavaScript click tricks. Is there a workaround to enable autoplay? Plunker <script>window.twttr = (function(d, s, id) { v ...

What is the best way to tally the number of fields in a JSON file based on their values

I'm relatively new to JavaScript and have a question that may seem basic. I've been struggling to find the answer, possibly because I'm not using the correct terminology. My goal is to count the number of "active" fields in a JSON file that ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

A guide on implementing an asynchronous timeout error handler in feathers

Is there a way to implement an async-function timeout error handler as a hook in Feathers that is located in the service file to manage promises within hooks? This post was created at the suggestion of @Bergi on my previous question If you are interest ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Guide to transferring filtered data to the controller

As I work on designing a user interface for managing project applications, one of the key functionalities is the ability to filter applications by their type. Within the UI, there is a prominent button labeled select ALL which, when clicked, is meant to se ...