Issue with Vue.js custom directive not automatically updating the state

I'm having trouble understanding why my directive isn't updating the disabled state of elements when there is a change in the model. Can someone help me identify the issue?

import { DirectiveOptions } from 'vue';    

const disableAllDirective: DirectiveOptions = {

componentUpdated: function (el, binding) {
    if (!binding.value) return;
    const tags = ["input", "button", "textarea", "select"];
    tags.forEach(tagName => {
        const nodes = el.getElementsByTagName(tagName);
        for (let i = 0; i < nodes.length; i++) {
            (<HTMLInputElement>nodes[i]).disabled = true;
            (<HTMLInputElement>nodes[i]).tabIndex = -1;
        }
    });
}
};

export default disableAllDirective;

This is how I'm using the directive:

<div class="col-5" v-disableAll="!selectedBusinessId">
                    <div class="form-row">
                        <label class="col-1 pt-1 col-form-label-sm">Search:</label>
                        <div class="col-6 form-inline">
                            <input id="txtClientSearch" @change="searchClients" v-model.lazy="clientSearchTerm" placeholder="Facility / Client Name" class="form-control" autocomplete="off" />
                            <input id="txtClientIdSearch" @change="searchClients" v-model.lazy="clientIdSearch" v-validate="'between:1,32767'" data-vv-as="Customer Number" placeholder="Number" class="form-control number-without-spinner" autocomplete="off" type="number" />
                            <button v-on:click="searchClients" class="btn btn-outline-secondary btn-sm form-control-xsm"><i class="fa fa-search"></i></button>
                            <button v-on:click="onClearSearchClick" class="btn btn-outline-primary btn-sm form-control-xsm"><i class="fa fa-times"></i></button>
                        </div>
                        <div class="col-auto form-check form-check-inline checkbox checkbox-primary">
                            <input v-model="showInactiveClients" v-on:change="searchClients" id="chkInactive" class="form-check-input" type="checkbox" value="inActive">
                            <label class="form-check-label no-padding" for="chkInactive">Show Inactive</label>
                        </div>
                    </div>
                </div>

Answer №1

After some investigation, I discovered a fundamental logic error - the function was exiting prematurely when the binding value was false, instead of correctly setting the 'disabled' attribute based on the binding value.

Here is the revised code:

import { DirectiveOptions } from 'vue';    

const disableAllDirective: DirectiveOptions = {

componentUpdated: function (el, binding) {
    const tags = ["input", "button", "textarea", "select"];
    tags.forEach(tagName => {
        const nodes = el.getElementsByTagName(tagName);
        for (let i = 0; i < nodes.length; i++) {
            (<HTMLInputElement>nodes[i]).disabled = binding.value;
            (<HTMLInputElement>nodes[i]).tabIndex = -1;
        }
    });
}
};

export default disableAllDirective;

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

Determining in Angular 8 whether a value has been altered by a user or by a method call

Within my select element, the value is currently being assigned through an ngOnInit call. Here is an example of the HTML code: <select name="duration" [(ngModel)]="exercisePlan.duration" (ngModelChange)="onChange($event)"> <option *ngFor="l ...

Associate the generic operator <T> with a FunctionConstructor

In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON. Here is how it looks like: export function deserializeJSON<T>(JSONString: string, ty ...

One way to consolidate multiple components in a single location without altering user-input data

I currently have 3 separate components, namely PersonalInfoComponent, EducationalInfoComponent, and ExperienceComponent. These components are all being displayed within the ResumeComponent. The issue I am facing is that when a user enters information in t ...

Differentiating TypeScript classes is important in situations where they would normally be treated as equivalent

Looking to add a lightweight layer on top of Float32Array to create vec2 and vec3's. Check out the example below: class vec3 extends Float32Array { // w : number; constructor() { super(3); // this.w = 1; } static add3(x: ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Unable to iterate over a 2D array using 'rows' in JavaScript or TypeScript

Imagine I need to generate a 2D array with this specific structure: [0, 1, 1, 1] [1, 0, 0, 0] [1, 0, 0, 0] To achieve this, I first initialized a 2D array with 0 values: function createGrid(m: number, n: number): number { let grid: number[][] = new Ar ...

A class in Typescript that provides utility functions for managing React components

I am currently working on a TypeScript React project and trying to create some utility classes. I am encountering difficulties when attempting to return a React component this way, and I'm unsure of the best approach. I keep receiving the error "refer ...

Transferring information between components using TypeScript and ReactJS via API calls

I am currently in the process of learning TS and I'm attempting to develop an application that retrieves data from an API, displays the results, and opens a modal with additional details when an item is clicked. However, I am facing an issue where my ...

Accept an empty string as the defaultValue, but disallow it during validation using Zod, react-hook-form, and Material UI

Currently, I am working with material ui components alongside react-hook-form and zod validation in my project. One of the challenges I encountered is with a select field for a bloodType: const bloodTypes = [ "A+", "A-", "B+", ...

How to Avoid Name Conflicts when Importing Modules in Angular 2?

I recently experienced a potential name collision issue, as I inadvertently created a class with the same common name Message that already exists in PrimeNG: import {Message} from "primeng/primeng"; import {Message} from "./dto"; Since it was my own code ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Uncovering the origins of computed object keys in TypeScript

I am currently working on a project where I need to easily define and use new plugins using TypeScript in my IDE. My folder structure looks like this: src │ ... └── plugins └── pluginA | index.ts └── pluginB | index. ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Issue with argument in function overloading

When working with multiple overloading functions in this code: export function rect(a: Point, b: Point): Rect; export function rect(a: Point, b: number|Point, c?: number): Rect; export function rect(a: number|Point, b: number|Point, c?: number, d?: number ...

Using TypeScript absolute imports from another project for standard TypeScript files and declarations at a global scope

We are currently considering migrating a large JavaEE code base to TypeScript. Within this environment, there are multiple projects with intricate directory structures and JavaScript code that heavily relies on global variables across all projects. Althou ...

What is the best way to specify data types for all attributes within an interface?

In building an interface for delivering strings in an i18n application: interface ILocaleStringsProvider { 'foo': string 'bar': string 'baz': string 'blablabla': string // numerous other string properties ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

Utilizing Angular Validators.email with the ability to accept null values

In my .ts file, I have an Angular validator set up like this: this.detailsForm = formBuilder.group( { email: ['', Validators.compose([Validators.email])] }); While this setup works fine, the email validator also applies the required validat ...

Issue with Path Alias Functionality in Bun Project Despite Accurate Configuration

I followed a guide to configure path alias at , but unfortunately, it's not working as expected. Recently I started a new Bun project with the intention of migrating a Node app to Bun. Here are the steps I took: Create a directory and initialize t ...

Extending interfaces in Typescript is a flexible and versatile feature

I currently have two interfaces, with one extending the other. However, I am looking for a way to extend the first interface and make all of its types optional without having to duplicate all the definitions in the second interface. This would eliminate th ...