Saturday, April 20, 2024
HomeJavaScriptThe inheritAttrs Choice in Vue

The inheritAttrs Choice in Vue


Sep 26, 2022

By default, attributes on the element “fall by way of” to the rendered component.
Within the following instance, the top-level <div> within the MyComponent template will inherit the class="style-div" attribute.


Vue.element('MyComponent', {
  template: `<div>Hi there World</div>`
});


<MyComponent class="style-div" />

In different phrases, the rendered component would appear like the next.

<div class="style-div">Hi there World</div>

inheritAttrs

Setting inheritAttrs to false prevents this fall by way of conduct.
Within the following instance, the <div> in MyComponent will not inherit the class attribute, or some other attribute.

Vue.element('MyComponent', {
  inheritAttrs: false,
  template: `<div>Hi there World</div>`
});

The rendered component would appear like the next.

<div class="style-div">Hi there World</div>

We discover inheritAttrs is beneficial in circumstances the place you wish to outline an inside occasion handler that fires the user-specified occasion handler.
For instance, we use inheritAttrs for our async-button element, which executes an async perform when the button is clicked and disables the button in the course of the async perform.
The async-button element must execute some logic to disable itself, along with executing the user-specified @click on handler.

app.element('async-button', {
  knowledge: () => ({
    standing: 'init'
  }),
  inheritAttrs: false,
  strategies: {
    
    
    async handleClick(ev) {
      if (this.standing === 'in_progress') {
        return;
      }
      this.standing = 'in_progress';
      strive {
        
        
        
        await this.$attrs.onClick(ev);
      } catch (err) {
        this.standing = 'error';
        throw err;
      }
      this.standing = 'success';
    }
  },
  computed: {
    
    
    
    attrsToBind() {
      const attrs = { ...this.$attrs };
      delete attrs.onClick;
      delete attrs.disabled;
      return attrs;
    },
    isDisabled() 
  },
  template: template
});

Beneath is the HTML for the async-button element.
Observe that v-bind binds any further attributes, aside from
disabled and onClick.

<button v-bind="attrsToBind" :disabled="isDisabled" @click on="handleClick">
  <slot></slot>
</button>


Vue Faculty has a few of our favourite Vue
video programs. Their Vue.js Grasp Class walks you thru constructing an actual
world utility, and does a terrific job of educating you the right way to combine Vue
with Firebase.
Test it out!


Extra Vue Tutorials

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments