2024-03-19
Vue.js code example with extends

Extending components, composition with Vue.js

https://sylvainleroy.com/wp-admin/options-general.php?page=ad-inserter.php#tab-2

This article will illustrate how to 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:

Contents

Using a Mixin

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

The other way, more powerful, allow a child component to almost everything from the parent component.

To use it, declares your parent component like a normal Vue.js component.

And then, using the keyword your child component will inherit everything from the and the props.


export default {
  name: "CustomerLinkTable",
  props: [],
  extends: AbstractTable,  
.../...
};

 

Interesting references

You may be interested by

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 knowledge and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)

View all posts by Sylvain Leroy →