0

Extending components, composition with Vue.js

Vue.js code example with extends
Bookmark this on Hatena Bookmark
Share on LinkedIn
Pocket

This article will illustrate how to some parts or a whole component. We’ll look at two different practices : mixins and extends.

Extending a component can at least be performed in two way:

  • using a
  • using extends

Using a Mixin

According the official documentation of Vue, a mixin allow the developer to mix functions and of two 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

You may be interested by

Share on LinkedIn
Pocket

Sylvain Leroy

Senior Software Quality Manager and Solution Architect in Switzerland, I have previously created my own company, Tocea, in Software Quality Assurance. Now I am offering my knowledges and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)