“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

demand

The front end now has a lot of components, it is also very convenient to use, so that we can not repeat the wheel, save a lot of development time, but also make the front end development become a lot easier.

However, every once in a while a component version we use has a bug or doesn’t quite meet our needs, and we just happen to meet it (after all, bosses aren’t gods). At this time, change a component library is too troublesome, rewrite a component, time-consuming and too long, this time can consider rewriting the method in the component

implementation

Let’s take vue+ Element as an example. Let’s say we want to override the El-Button click method in the Element library. We want to bury each click event.

Looking at the code, we have two opportunities to override el-Button’s method.

The first time, when the el-button is introduced, if the el-button is introduced globally, then it is overwritten at this time, which is for all el-buttons, as follows:

The import ElementUI from 'element - the UI ElementUI. Button. The methods. The handleClick = function (evt) {/ / this here is to point to the Button Console. log('evt ->', evt, this)Copy the code

$refs = $refs; $refs = $refs; $refs = $refs;

Mounted () {this. $refs. MyButton, handleClick = (evt) = > {/ / this point to the console is the current page. Here the log (' evt -- >, evt, }}Copy the code

Attention, please take a closer look at the code below

Mounted () {this. $refs. MyButton, handleClick = function (evt) {/ / this is null the console. Here the log (' evt -- >, evt, }}Copy the code

The first method this refers to the current page, and the second method this refers to null. To retrieve a button object, use a closure as follows:

Mounted () {this. $refs. MyButton, handleClick = (evt) = > {the console. The log (' evt -- >, evt, enclosing $refs. MyButton) / / unified buried point processing}}Copy the code

Online also has some direct rewriting the entire component method, is also useful to myself, but a lot of complex components in too many references, rewrite a component alone, need a component will be introduced, write up a little trouble, so can pass the object directly modifying internal methods, more is recommended to use this method.