undefinedfix
Sign in

Vue global disable component

FrankT edited in Tue, 15 Nov 2022

For Vue + antdv projects, there is a page in two states recently: edit state and view state. In edit state, you can modify the page. However, in view state, all modifiable parts of the page should be disabled. However, there are too many elements in the page, and it is not convenient to add disabled in every place, Later, the newly developed components also need to take into account this part of the function, which is difficult to maintain. Therefore, consider a scheme that can be directly disabled globally, instead of adding disabled method to each component. Do you have an idea?

At present, one of the ideas is to modify it directly props.disabled It's too violent, but there's no better way to think about it. I hope a friend can think of some advice

Vue.use({

    install(Vue) {

        Vue.mixin({

            created() {

                const { $props, $route } = this;

                if ($props && $route) {

                    const desc = Object.getOwnPropertyDescriptor($props, 'disabled') || {};

                    const originGetter = desc.get;

                    Object.defineProperty($props, 'disabled', {

                        ...desc,

                        get() {

                            if ($route.query.readMode !== undefined) {

                                return true;

                            } else {

                                return originGetter && originGetter.call(this);

                            }

                        }

                    });

                }

            }

        });

    }

});
3 Replies
Cube
commented on Tue, 15 Nov 2022

< fieldset > can be realized to a certain extent. To a certain extent, it is because the date picker component in ant cannot be disabled through fieldset. Maybe it can only be realized by secondary encapsulation.

samarathunga
commented on Wed, 16 Nov 2022

There are three ways I can think of:

  1. All the disabled attributes of input components in the form are bound to the same value. Just change the value. The disadvantage is that the individual input box needs to be prohibited separately, and the solution is that the special input box is bound to other values and controlled separately.
  2. The cost of secondary packaging is a bit high.
  3. The direct parent component this. $refs gets the references of all the child components, traverses the child components, and assigns the disabled property to true respectively. Vue will have a warning, which will destroy the design principle of Vue components and is not recommended.
Fastful
commented on Wed, 16 Nov 2022

Control how to use CSS style

.disabled{
    pointer-events: none;
    opacity: 0.6;
}