This article will illustrate how to extends some parts or a whole Vue.js component. We’ll look at two different practices : mixins and extends.
Extending a Vue component can at least be performed in two way:
- using a mixin
- using extends
Using a Mixin
According the official documentation of Vue, a mixin allow the developer to mix functions and props of two data structure to obtain a merged component.
I won’t spend too much time on the explanation since the things are quite easy :
First declare an object that contains some Vue component methods or structures.
export default {
computed: {
websiteUUID() {
return this.$route.params.websiteId;
},
reportId() {
return this.$route.params.reportId;
},
crawlId() {
return this.$route.params.crawlId;
},
websiteSelected() {
return this.$route.params.websiteId != null;
},
currentWebsite() {
return this.$route.params.websiteId;
},
currentLink() {
return this.$route.params.pageId;
},
currentWebsiteName() {
if (this.$route.params.websiteId) {
return this.$store.getters.websiteName(this.$route.params.websiteId);
}
return "";
},
currentDomain() {
if (this.$route.params.websiteId) {
return this.$store.getters.websiteDomain(this.$route.params.websiteId);
}
return "";
},
crawlIdRef
: function () {
return "crawl-" + this.$route.params.crawlId;
},
}
}
And from the component that wish to inherit these computed props, simply add the mixin instruction in the component declaration.
// Child.js
export default {
props: [],
mixins: [parentComponent]
}
Mixin are limited to what can be declared inside the component declaration and the child component cannot inherit the template.
Using extends
The other way, more powerful, allow a child component to extends almost everything from the parent component.
To use it, declares your parent component like a normal Vue.js component.
And then, using the extends keyword your child component will inherit everything from the template and the props.
export default {
name: "CustomerLinkTable",
props: [],
extends: AbstractTable,
.../...
};
Interesting references
- https://vuejsdevelopers.com/2017/06/11/vue-js-extending-components/
- https://stackoverflow.com/questions/39478032/vue-js-pass-function-as-prop-and-make-child-call-it-with-data
- https://alligator.io/vuejs/composing-components/