DEV Community

Cover image for 10 Tips to Write Cleaner Vue.js Code
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

10 Tips to Write Cleaner Vue.js Code

When transitioning from one project to another (for example when changing jobs) there is always this period of time when I need to adjust to the new project flow and development process.

There are things that are unique for certain projects but in Vue, there are things that are considered good practices for building clean and maintainable Vue based projects.

In this article, I would like to list these best practices so that you can start using them in your Vue projects :)

Enjoy!

🟢 10 Tips to Write Cleaner Vue.js Code

Clean and maintainable code is the backbone of any successful application. Vue.js, with its intuitive API, makes it easy to write clean code, but there’s always room for improvement. Here are 10 actionable tips to help you write cleaner Vue.js code.

1. Use the Composition API Wisely

Break large logic into smaller, reusable composables to maintain modularity and readability.

Example: Instead of cramming all logic into a setup() function, create custom hooks for distinct functionalities.

2. Follow Vue’s Naming Conventions

Use PascalCase for component file names and optionally kebab-case for template usage.

Example: Name your component UserProfile.vue and use it as <UserProfile /> or optionally <user-profile /> in templates.

3. Avoid Overusing Vuex or Pinia

Keep transient UI states (e.g., modal visibility) local to the component rather than in global state management.

Example: Use ref or reactive for temporary states.

4. Utilize Slots Effectively

Use named slots for better flexibility in reusable components and document their usage.

Example: Create a Card component with <slot name="header"></slot> for customizable headers.

5. Leverage Scoped Styles

Use scoped styles in <style scoped> tags to prevent CSS conflicts.

Example: Apply component-specific styles without affecting other parts of the application.

6. Write Reusable Components

Break down UI elements into reusable, focused components, avoiding overly generic designs.

Example: Instead of hardcoding a button, create a configurable Button component that supports props for different styles.

7. Handle Asynchronous Code Gracefully

Use async/await for API calls and handle errors using a central utility function.

Example: Create a useApi composable to encapsulate API logic and error handling.

8. Document Props and Emit Events

Clearly define and document props and events using props and emit annotations or TypeScript.

Example: Use defineProps and defineEmits in Vue 3 for clarity and type safety.

9. Lint Your Code

Set up ESLint and Prettier with Vue-specific configurations to enforce code quality and consistency.

Example: Integrate linting into your CI/CD pipeline to automate code reviews.

10. Keep Templates Simple

Avoid placing complex logic in templates; instead, use computed properties or methods.

Example: Replace v-if="list.filter(item => item.active).length > 0" with a computed property activeItems.

📖 Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

✅ Summary

Well done! By following these tips, you’ll create Vue.js applications that are easier to maintain, scale, and debug. Clean code benefits not just the current project but also future developers who may work on it. Start small by implementing a few of these practices today!

Take care and see you next time!

And happy coding as always 🖥️

Top comments (10)

Collapse
 
hinogi profile image
Stefan Schneider • Edited

I got a bonus. If you use vite, you might experience different parsing behavior especially when using pug as template language.
In that regard, try to avoid typescript generics in templates.

v-if="list.filter((item: Maybe<ListItem>) => item.active).length > 0"
Enter fullscreen mode Exit fullscreen mode

this will works in vue, but not in the vite devserver since the vite-vue-plugin will complain about no end tag for template because it thinks the generic is also a tag.

Collapse
 
fabio_cardoso_52397447e3e profile image
Fabio Cardoso

Another tip is always you need use a Lot of if and else in your code maybe you should create custom directives in vue. Like some example

From <Button v-if="user.isAdmin" /> to <Button is-admin />

Collapse
 
eastmann profile image
Maxim Klochkov

What do you mean by:

handle errors using a central utility function

Would share an example, please?

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

Hey there, I have answered it here dev.to/jacobandrewsky/comment/2kcgd :)

Collapse
 
eastmann profile image
Maxim Klochkov • Edited

Hi Jakub!

Thank you for your explanation! I got the idea and I tried handling errors with try/catch in the composable:

the composable handles the error returning to you the result that you can display to a user in a friendly way. And you don't need to write try/catch in every place to achieve that as it is handled by the composable

But when I use such fetch composable in a Vue component and if there is a network or API error I get unhandled promise error message in the console anyway if it is not wrapped in try/catch:

<script setup lang="ts">
import { onMounted } from "vue"
import { useFetch } from "../composables/useFetch.js"

const { data, loading, error, fetchData } = useFetch()

onMounted(async () => {
  await fetchData("https://dummyjson.com/users")
  // unhandled promise error message if something wrong...
})
</script>
Enter fullscreen mode Exit fullscreen mode

How should this console error be handled?

Thread Thread
 
jacobandrewsky profile image
Jakub Andrzejewski

Could you share your code of useFetch.js composable? Maybe some configuration is missing from there :)

Collapse
 
ciphernutz profile image
Ciphernutz

Awesome tips! These will definitely help in writing cleaner and more efficient Vue.js code.

Collapse
 
emercab profile image
Emerson Cabrera

I loved this post, thank you. Very useful tips.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

When using VueUse axios for example, you get a centralized approach to handle errors (the error property returned by the composable. This means that the composable handles the error returning to you the result that you can display to a user in a friendly way. And you don't need to write try/catch in every place to achieve that as it is handled by the composable.

If not using utility like the one above, you could create your own useApiClient composable that could be a wrapper around the fetch method that will also by default handle errors and populate a property to show you what the error code and message was.