Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field.

Rather than manually adding multiple event listeners like this:

<input type="text" name="firstName" 
v-model="form.firstName.value" 
@blur="form.firstName.onBlur" 
@focus="form.firstName.onFocus" 
@change="form.firstName.onChange"
[...]
 />

We can simply do this:

<input type="text" name="firstName" v-form-control="form.firstName" />

And let the directive handle everything behind the scenes.

However, I am struggling to figure out how to add a directive to the input element from within the FormControl directive itself.

I considered trying something like this:

Vue.directive('form-control', {
    bind: function(el: HTMLElement, binding: DirectiveBinding) {
        const formControl: FormControl = binding.value;
        el.addEventListener('input', (event) => {
            formControl.updateValue(event.target.value);
        });
    },
});

But I feel like I am missing out on some of VueJS's capabilities by taking this approach. Manually attaching an input event may not be as reliable as using the v-model directive.

Is there a way to incorporate the original vue directives and events into an element from the bind method of a directive?

Thank you for your assistance!

Answer №1

The Vue directives originally serve as event handlers. V-model simplifies the syntax by incorporating :value=".." and @input="..".

Therefore, feel free to add your event listeners for standard DOM events (input, blur, focus, change).

In order to be processed by the JavaScript runtime, Vue directives are converted into regular event listeners - they do not persist at runtime, hence, their syntax cannot be manipulated dynamically.

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

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Vercel deployment encountered an AxiosError with a status code of 404

I am currently working on an API route called app/api/posts/route.ts, which is responsible for fetching all posts from my database using Prisma ORM. In the localhost environment, the database is hosted on my local PostgreSQL server. However, in production, ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

Add a preventDefault event listener to a submit button that triggers a specific function

$(function() { $('#login').submit(function(e){ preventSubmission(); e.preventDefault(); }); }); function preventSubmission() { $('#btnLogin').attr('disabled','disabled'); $("#btnLogi ...

Displaying component using VUEX getter in Vue.js

My main screen rendering code is set up to display components based on the value retrieved from vuex store. However, I've encountered an issue where the component does not reload when a mutation occurs. Any suggestions or tips on how to resolve this p ...

Guide to triggering a function upon selecting a row in a SyncFusion grid

My goal is to use a SyncFusion Vue Grid component and trigger a function when a row is selected. I attempted to include a column of edit buttons, but I am struggling to find the correct syntax to make these buttons call a function. Alternatively, I tried ...

The jQuery code is failing to affect a form that has been dynamically inserted into the DOM using AJAX

Utilizing jQuery's hover event, my app includes a standard star voting functionality. The logic for star voting was previously rendered with the rest of the page upon the initial DOM load through an HTML request. However, I am interested in relocating ...

Leveraging async/await in Firebase functions along with the once() method

Recently diving into the world of TypeScript, I've been navigating my way through with relative ease. However, I've encountered a perplexing issue while working with async/await. The problem lies within this code snippet - the 'await' ...

How come the pop-up isn't displaying in the middle of the screen?

I have encountered a positioning issue while using a semantic modal with Angular. The problem arises when I try to display the modal as it does not appear in the correct position. https://i.sstatic.net/o033E.png Below is the code snippet from my HTML fil ...

What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below: declare global { interface Window { System: Sy ...

Using Laravel to retrieve data from an API and display it with VueJS

Recently delving deeper into the world of Laravel, I found myself pondering the most effective method to pass data from my controller to my Vue component. While I have grasped the concept of passing data as a prop, I am struggling to achieve the desired r ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

Jetbrains WebStorm has issued a caution about experimental support for decorators, noting that this feature is in a state of flux and may

No matter how long I've been searching, I can't seem to get rid of this warning even after setting the experimentalDecorators in my tsconfig file. I'm currently working on an Ionic project with Angular, using webstorm by JetBrains as my IDE. ...

AngularJS directive element not displaying CSS styles properly

I've been grappling with this issue for the past few days and I just can't seem to crack it. Whenever I try adding a class to an AngularJS element directive, the styling appears in the code view of my browser (Chrome), but the styles themselves ...

Adding custom styles to Material-UI components

` import React, { Component } from 'react'; import Header from './Components/UI/header'; import { Box, Paper } from '@material-ui/core'; import { ThemeProvider, withStyles} from '@material-ui/core/styles'; const ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

Issue with Electron dialog.showOpenDialog() Filters malfunctioning

Recently, I've been working on a modified version of an IDE on GitHub and encountered a major issue where the files were being saved to cookies instead of the computer. This prompted me to find a way to save and open files efficiently. While I managed ...

Blend express router by chaining the (.route) method with other HTTP methods like (.get, .post, etc) to create

Here is my code structure: let router = require( 'express' ).Router(); Later on, I define my routes like this: router .route( '/' ) .get( listMiddleware ); router .route( '/:id' ) .get( getOneByIdMiddleware ...

Why does my VueJS method only execute after I save changes in VS Code instead of reloading the page? Can someone provide assistance?

Whenever I refresh the page, the console.log inside the method does not get executed until I make a change in VSC and save it. Is the show/hide modal for the form causing this issue? I tested removing the toggle but the problem persisted. Please refer to ...

How can we efficiently link data to custom objects (models) within a different class while fetching data from the server using the http.get() method in Angular CLI?

Currently in the process of developing an Angular-Cli application that involves multiple models with relational data tables. When fetching data from the server, I need to map this data to corresponding model objects. I've experimented with creating a ...