Home > Mobile >  Is it possible to use a SFC Vue component as a mixin?
Is it possible to use a SFC Vue component as a mixin?

Time:11-02

For example, I have a component written in SFC format:

// Parent.vue
<template>
  <div>
    {{ txt }}
  </div>
</template>

<script>
export default {
  name: 'ParentComponent',
  data() {
    return {
      txt: 'Hello, world! I\'m Parent'
    }
  },
  methods: {
    sayHello() {
      console.log(this.txt);
    }
  }
}
</script>

And I would like to reuse the component above from which I can extend:

// Child.vue
<template>
  <div>
    {{ txt }}
  </div>
</template>

<script>
import ParentComponent from './Parent';

export default {
  name: 'ChildComponent',
  mixins: [ParentComponent],
  created() {
    this.sayHello(); // 'Hello, world! I'm Parent'
  }
}
</script>

My questions:

  1. Is it possible to use like this fashion?
  2. If possible, then I can understand that the vue component properties like data, methods, ... will be integrated in ChildComponent as that is a basic behavior of Vue mixin. But what about <template> part? How the markup parts are integrated together? Or is it ignored so that the only <script> part is merged?

CodePudding user response:

1- Yes it's possible but using extends option instead of mixins :

<template>
  <div>
    {{ txt }}
  </div>
</template>

<script>
import ParentComponent from './Parent';

export default {
  name: 'ChildComponent',
  extends: ParentComponent,
  created() {
    this.sayHello(); 
  }
}
</script>

2 - This inherits only the extended component options.

  • Related