The composition option are used to define the common feature which can be reused by the component. It can be used to share data or other option as per the requirement of the application.
1. | parent |
2. | mixins |
3. | extends |
4. | provide / inject |
Parent
The parent instance can be accessible once the instance is created using instance property .$parent. It can be used to communicate between parent and child and the child will be pushed into the parent’s $children array.
Access parent in child component
1 <template>
2 <div>Parent component accessing Home component property and method</div>
3 </template>
4
5 <script>
6 import Vue from "vue";
7
8 export default {
9 name: "ReusableView",
10 mounted: function () {
11
12 this.$parent.update(5);
13
14 this.$parent.value = 5;
15 },
16 };
17 </script>
18
Mixins
The mixins option allows to specify flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options.
1 <script>
2 const data = { value: 0 };
3 export default {
4 data: () => data,
5 methods: {
6 print: function () {
7 console.log("Current value is : " + this.value);
8 },
9 },
10 watch: {
11 value: function (newValue, oldValue) {
12 console.log("Watch function " + oldValue + " changed to " + newValue);
13 },
14 },
15 };
16 </script>
Extends
The extends option allows to extend existing vue component either a plain options object or a constructor without having to use Vue.extend. The primarily use of the option is to make it easier to extend between single file components.
1 <template>
2 <div>
3 <div>Child component extends Parent</div>
4 <button @click="increament">Increase</button>
5 </div>
6 </template>
7 <script>
8 import ParentView from "@/components/ParentView.vue";
9
10 const data = { value: 10 };
11
12 export default {
13 name: "ChildView",
14 data: () => data,
15 methods: {
16 increament: function () {
17 this.value++;
18
19 this.print(this.value);
20 },
21 },
22
23 extends: ParentView,
24 };
25 </script>
26
provide / inject
The provide and inject option used together in Vue component for sharing data to the multi level component hierarchy or nested component as long as they are in the same parent chain.
1 <template>
2 <div class="home">
3 <ChildView />
4 </div>
5 </template>
6
7 <script>
8 import ChildView from "@/components/ChildView.vue";
9
10 export default {
11 name: "HomeView",
12 components: {
13 ChildView,
14 },
15
16 provide: {
17 data: { name: "Vue Js", version: "2+" },
18 },
19 };
20 </script>
Related options for your search