All posts

Vue.js Production Best Practices

Essential Vue.js best practices for production apps covering state management, component patterns, performance optimization, and error handling.

Vue.js Production Best Practices

Vue's flexibility means you need discipline to keep large applications maintainable. Here are proven production patterns.

State Management with Pinia

import { defineStore } from 'pinia';

export const useOrderStore = defineStore('orders', () => {
  const orders = ref<Order[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  async function fetchOrders() {
    loading.value = true;
    error.value = null;
    try {
      orders.value = await api.getOrders();
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to fetch orders';
    } finally {
      loading.value = false;
    }
  }

  return { orders, loading, error, fetchOrders };
});

Component Design Patterns

Keep components focused:

<!-- Smart component: handles data -->
<script setup lang="ts">
const store = useOrderStore();
onMounted(() => store.fetchOrders());
</script>
<template>
  <OrderList :orders="store.orders" :loading="store.loading" />
</template>

<!-- Dumb component: pure presentation -->
<script setup lang="ts">
defineProps<{
  orders: Order[];
  loading: boolean;
}>();
</script>

Type-Safe Props

interface Props {
  title: string;
  items: Item[];
  variant?: 'primary' | 'secondary';
}

const props = withDefaults(defineProps<Props>(), {
  variant: 'primary',
});

Performance Optimization

<!-- Use v-memo for expensive list items -->
<div v-for="item in items" :key="item.id" v-memo="[item.updated]">
  <ExpensiveComponent :data="item" />
</div>

<!-- Lazy load routes -->
const routes = [
  {
    path: '/dashboard',
    component: () => import('./views/Dashboard.vue'),
  },
];

Error Handling

// main.ts
app.config.errorHandler = (err, instance, info) => {
  console.error('Vue error:', err, info);
  // Report to error tracking service
};

app.config.warnHandler = (msg, instance, trace) => {
  // Capture Vue warnings in development
};

Security

  • Never use v-html with user input
  • Sanitize data before rendering
  • Use CSP headers to prevent XSS
  • Validate all form inputs

Integrate Bugsly to capture Vue errors in production with full component hierarchy context, making it easy to trace exactly which component and user action triggered an issue.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free