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.
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!
You should read it
- 6 logical puzzles for children that adults must 'headache'
- Apple launches new professional music editing software
- Simple ways to reuse expired products
- How to reuse and combine Google Forms with FormRecycler
- Mask reuse: Is microwave steaming safe from Covid-19 virus?
- 7 creative ways to reuse or recycle old speakers
- Handling errors in JavaScript
- How to Make a GUI Grid in Java
May be interested
- Tiny11 core, Windows 11 version weighs only 2GB, runs smoothly on PC with 4GB RAMtiny11 core is a brand new stripped down version of windows 11 created by @ntdev_, the modder who created modified versions of windows that make the operating system lighter and smoother.
- If you see your information using Google Search, you can use this tool to remove itgoogle has provided a hidden feature that helps you track and protect your personal data. this means that if someone wants to find information about you, they will most likely search on google first.
- The difference between quantum computers and supercomputerstwo particularly advanced inventions, supercomputers and quantum computers, have many applications and potential. but what is the difference between a supercomputer and a quantum computer, and which is better?
- Xiaomi officially launched HyperOS: Super light, supports many AI features, improves performancexiaomi has officially launched the new hyperos user interface with many changes compared to the miui version on its previous smartphones.
- Microsoft makes glass hard drives that last 10,000 yearsmicrosoft's glass hard drive project called silica was tested by the company four years ago. the advantage of recording data on glass is that it is not damaged and can be preserved for up to 10,000 years without needing to be copied again.
- 9 pros and cons of using a local LLMsince chatgpt emerged in november 2022, the term large language model (llm) has quickly moved from a term reserved for ai enthusiasts to a buzzword on everyone's lips.