Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (158).NET Core  (28).NET MAUI  (44)Angular  (65)ASP.NET  (50)ASP.NET Core  (77)ASP.NET MVC  (88)Azure  (32)Blazor  (141)DocIO  (23)Essential JS 2  (80)Essential Studio  (171)File Formats  (27)Flutter  (121)JavaScript  (172)Microsoft  (112)PDF  (66)React  (52)Succinctly series  (126)Syncfusion  (571)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (35)Webinar  (30)Windows Forms  (58)WinUI  (43)WPF  (134)Xamarin  (149)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (117)Chart  (56)Cloud  (11)Company  (445)Dashboard  (7)Data Science  (3)Data Validation  (6)DataGrid  (54)Development  (354)Doc  (7)DockingManager  (1)eBook  (95)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (17)File Manager  (4)Gantt  (11)Gauge  (9)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (289)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (29)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (21)Solution Services  (2)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (89)UI  (200)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (23)Visual Studio Code  (14)Web  (326)What's new  (193)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Can the Composition API Replace Vue Mixins?

Can the Composition API Replace Vue Mixins?

Vue Mixins is a very popular concept for reusable code sharing between components. However, the Composition API introduced in Vue 3 provides much better functionalities to implement reusable components.

This article will go through the concept of Mixins, the limitations of Mixins, and how the Composition API can address these limitations.

What are Mixins?

Mixins are blocks of code clearly defined in a prescribed manner by Vue. We can share them among the Vue components to implement common functionalities. So, Mixins help developers avoid unnecessary code repetitions and reuse functionalities across a Vue application.

Recap on Mixins Concept

When shared functionalities and properties have to be implemented in multiple Vue components, they can be extracted into a separate module, as shown in the following code.

//MixinComponent.js

export default{
  data: ()=>({
    reuseData: "Mixin data";
  }),
  methods: {
    reuseMethod() {
      console.log('Hello from mixin!')
    }       
  }
}

A Mixin object can contain any component option—such as data, methods, etc.—as given in the previous example.

To use the Mixin in any component, you simply have to import the Mixin module and assign it to the mixins configuration property in the component.

<!--MyComponent.vue-->
<template>
 <div>
    <h1>This component uses Mixins.</h1>
    <h2>Mixin data {{reuseData}}</h2><h2>Calling Mixin method {{reuseMethod()}}</h2>
 </div>
</template> 

<script>
//Import MixinComponent.js
import myMixin from './MixinComponent.js'
export default {
  mixins:[myMixin],
  data:()=>({
    componentData: 0
  }),
  methods:{
    componentMethod() {...}
  }
}
</script>

At runtime, the options specified in the Mixin will be available as options and will be “mixed” into the consuming component’s options.

Why are Mixins not ideal?

Even though Mixins were the primary method to implement reusability in Vue 2, some drawbacks came along with them.

  1. Mixins are conflict-prone

When there are multiple Mixins used in a component, all the properties of the Mixins will be merged into the component. As the code base grows, it’ll get increasingly harder to track and avoid property name conflicts between the Mixins and the components, even with the merge strategies introduced by Vue.

  1. Harder to track properties’ origins

Since there’s no hierarchical relationship between Mixins and the components consuming them, components can use data properties defined in a Mixin. On the other hand, Mixins can also use data properties from components, assuming they are already defined.

As a result, properties may seem to appear out of nowhere, mainly when components use multiple Mixins. This could put developers in a messy situation because it’s hard to debug the code and identify the modules from which the conflicts arise.

  1. Limited Reusability

The flexibility provided by Mixins is quite limited, as Mixins do not allow passing parameters to change the logic implemented in them.

Role of Composition API in Replacing Mixins

Vue introduced the Composition API to address the issues resulting from the fragmented behavior of Vue Mixins and to provide functionalities to arrange code blocks related to the same logical concerns.

Composition API is a built-in feature of Vue 3 and a plug-in in Vue 2.

Implementing Reusable Components with Composition API in Vue 3

When using Composition API, Reusable components are defined as JavaScript variables. We can return those JS variables from a component option named setup instead of defining the component functionalities in terms of object properties such as states, methods, etc.

Here’s a small demonstration of this process.

The useComp.js component shows how to define a component as a JavaScript function to reuse it in any other component using the Composition API.

//useComp.js

//import ref function to define reactive properties
import {ref} from 'vue'
export default function useComp(){

    const reuseData = ref ("Reusable data")
    function reuseMethod() {
        console.log(reuseData.value);
        console.log('Hello from Reusable method!')
    }
    return {
        reuseData,
        reuseMethod
    }
}

In the previous component, the ref function from Vue 3.0 is used to create a reactive reference to the variables so that they can be safely passed across the application without worrying about losing their reactivity along the way.

After defining the reusable features, we can easily import the component to any consuming component. The features will be returned from the setup() function, which is the entry point for the Composition API.

<!--MyComponent.vue-->
<template>
 <div>
   <h1>This component uses Component API.</h1>
   <h2>Reusable data {{reuseData}}</h2><h2>Calling the reusable method {{reuseMethod()}}</h2>
 </div>
</template> 

<script>
 //Import useComp.js
 import useComp from './useComp.js'

 export default {
    //Use setup option as the entry point to the Composition API
    setup(){
      const {reuseData, reuseMethod} = useComp()
      return{
        reuseData,
        reuseMethod
      }
    }
  }
</script>

That’s it! We can easily implement the same functionalities provided by Mixins using the Composition API.

Do check out the official documentation to learn more about the Composition API.

Advantages of Composition API over Mixins

There’s no functionality difference between the Mixins approach and the Composition API approach. However, Composition API provides clear and straightforward solutions to all the drawbacks of Mixins.

  1. No More Conflicts!

As shown in the example in the previous section, any states, variables, or methods reused from a Composable (i.e., a function using the Composition API) have to be explicitly defined in the setup() method of the consuming component.

Therefore, naming collisions between multiple Composables and the consuming component won’t occur. Also, the developer will easily be able to identify the origin of every variable used in the component.

  1. More Flexibility

Unlike Mixins, we can pass parameters to Composables to alter their logic easily.

Let’s have a look at the following Composable that takes a parameter.

//useComp.js

//import ref function to define reactive properties
import {ref} from 'vue'
export default function useComp(initialParam = "Composable data"){

    const reuseData = ref (initialParam)
    function reuseMethod() {
        console.log(reuseData.value);
        console.log('Hello from Reusable method!')
    }
    return {
        reuseData,
        reuseMethod
    }
}

The useComp() Composable function takes initialParam as a parameter.

When calling the useComp() function from a consuming component, we can either pass a value to the initialParam or call the function without passing any parameter. In that case, the default value “Composable data” will be assigned to initialParam.

Conclusion

Even though Mixins are pretty straightforward to use in most cases, they have a few drawbacks, as discussed in this article.

The newly introduced Composition API provides more flexible and clean methods to overcome these difficulties and reuse components in a much easier way. Especially when it comes to implementing much larger and scalable applications, the Composition API takes over Vue Mixins.

I hope you got a better understanding of these two approaches for code reusability in Vue. So, next time you can be mindful when choosing between Mixins and the Composition API. Thank you for reading!

The Syncfusion Vue UI components library is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package.

For questions, you can contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top