How to reuse logic in Vue.js with composite components

Composable - Composable components are a simple upgrade that you should use with apps built with Vue 3 right away. Below are detailed instructions.

Composable - Composable components are a simple upgrade that you should use with apps built with Vue 3 right away. Below are detailed instructions.

How to reuse logic in Vue.js with composite components Picture 1How to reuse logic in Vue.js with composite components Picture 1

When programming, it is important to establish a codebase structure to reuse code whenever possible. Duplication can make the codebase bloated and debugging more complicated, especially in larger applications.

Vue simplifies code reuse across composite components. Composables are functions that encapsulate logic, and you can reuse them across projects to handle similar functionality.

Before Vue 3 introduced composability, you could use mixins to collect code and reuse it in different parts of the application. Mixins contain Vue.js options like data, methods, and product cycle hooks, allowing code reuse across multiple components.

To create mixins, you create a structure for each individual file, then include them and components by adding the combination to the mixins property in that component's selection object. For example:

// formValidation.js export const formValidationMixin = { data() { return { formData: { username: '', password: '', }, formErrors: { username: '', password: '', }, }; }, methods: { validateForm() { this.formErrors = {}; if (!this.formData.username.trim()) { this.formErrors.username = 'Username is required.'; } if (!this.formData.password.trim()) { this.formErrors.password = 'Password is required.'; } return Object.keys(this.formErrors).length === 0; }, }, };

This code shows the contents of the mixin for form validation. This combination contains two data properties - fromData and formErrors - initially set to empty values.

formData contains the input data for this form, including the username and password fields initialized as blank. formErrors represents this structure to contain the potential error message, which is also initially empty.

The mixin also contains a method, validateForm() , to check if the username and password are empty. If either field is empty, it populates the formErrors data attribute with an appropriate error message.

This method returns true for a valid form, when formErrors is empty. You can use a mixin by importing it into a Vue component and adding it to the mixin property of the Options object:

  {{ formErrors.username }}  {{ formErrors.password }}  

This example shows a Vue component written using the Options object method . The mixins property includes all the mixins you imported. In this case, the component uses the validateForm method from the formValidation mixin to notify the user whether or not the form submission was successful.

How to use ingredients that can be combined

A composite component is a standalone JavaScript file with functions tailored to specific concerns or requirements. You can leverage Vue's compositing API in a composite component using features like refs and computed refs.

Access to the component API allows you to create functions that integrate into a variety of components. These functions return an object that you can immediately import and compose into Vue components via the Composition API's setup function.

Create a new JavaScript file in the src folder to use a composable component. For larger projects, consider organizing a folder within src and creating separate JavaScript files for the different composable components, making sure to name them clearly for their intended use.

Inside the JavaScript file, define the function you need. Here is a refactoring of the formValidation mixin as a combined component:

// formValidation.js import { reactive } from 'vue'; export function useFormValidation() { const state = reactive({ formData: { username: '', password: '', }, formErrors: { username: '', password: '', }, }); function validateForm() { state.formErrors = {}; if (!state.formData.username.trim()) { state.formErrors.username = 'Username is required.'; } if (!state.formData.password.trim()) { state.formErrors.password = 'Password is required.'; } return Object.keys(state.formErrors).length === 0; } return { state, validateForm, }; }

This snippet starts by importing the react function from the vue package . It then creates an exportable function, useFormValidation() .

It works persistently by creating a response variable, state , that contains formData and formErrors properties . This fragment then handles form validation using a very mixin-like method. Finally, it returns the state variable and the validateForm function as an object.

You can use composable components by importing a JavaScript function from a file in your component:

  {{ state.formErrors.username }}  {{ state.formErrors.password }}  

After importing the useFormValidation composable component , the code deconstructs the JavaScript object it returns and continues validating the form. It reports whether the form was submitted successfully or an error occurred.

While mixins were useful in Vue 2 for code reuse, composable components have taken their place in Vue 3. Composables provide a more structured and maintainable method for reusing logic. in Vue.js applications, making it easier to build scalable web apps with Vue.

Hope this article is useful to you!

4 ★ | 1 Vote