typescriptvue.jsvuejs2vue-componentvue-class-components

What is the difference between extends and mixins when using the vue-class-component library?


Heads-up: We are using Vue 2 and are not planning to switch to the Composition API (yet). This question is about .

Question: The documentation of vue-class-components states that we can use "normal" extends to inherit from a single parent component, or to use the mixins helper function to inherit multiple mixins. In my understanding, a parent component is nothing else than a mixin (and vice-versa), thus I would like to know if the following code with a single parent component results in the same child components:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export class Parent extends Vue {
  p = 'P'
}

@Component
export class ChildOne extends Parent {
  created () {
    console.log(this.p)
  }
}

@Component
export class ChildTwo extends mixins(Parent) {
  created () {
    console.log(this.p)
  }
}

Solution

  • In that case the child components will behave the same way, both will inherit the p prop from the Super class.

    The main advantage of using mixins over extends is that you can inherit from multiple classes. Otherwise, if you just need to inherit from one parent class, IMHO then it makes no sense to use mixins

    Example

    // mixins.js
    @Component
    export class Rock extends Vue {
      rock = 'rock'
    }
    
    @Component
    export class Roll extends Vue {
      roll = 'roll'
    }
    
    import { Rock, Roll } from './mixins'
    
    @Component
    export class RockAndRoll extends mixins(Rock, Roll) {
      mounted() {
        // now that this is mounted, let's rock and roll
        saySomething()
      }
      
      saySomething() {
        console.log(`let's ${this.rock} and ${this.roll}!`)
      }
    }