DEV Community

Software Developer
Software Developer

Posted on

50 Most Useful Vue.js Snippets


I. Basic Component Structures

1. Functional Component (Vue 3 setup syntax)

<script setup>
const greeting = 'Hello World';
</script>

<template>
  <h1>{{ greeting }}</h1>
</template>
Enter fullscreen mode Exit fullscreen mode

2. Props with Type and Default

<script setup lang="ts">
import { defineProps } from 'vue';

const props = defineProps({
  name: { type: String, default: 'Vue User' }
});
</script>

<template>
  <h2>Hello, {{ props.name }}!</h2>
</template>
Enter fullscreen mode Exit fullscreen mode

3. Emit Custom Event

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['submit']);

function handleClick() {
  emit('submit', { success: true });
}
</script>

<template>
  <button @click="handleClick">Submit</button>
</template>
Enter fullscreen mode Exit fullscreen mode

II. Reactive State and Computed

4. ref for Reactive Primitive

<script setup>
import { ref } from 'vue';

const count = ref(0);
function increment() {
  count.value++;
}
</script>

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>
Enter fullscreen mode Exit fullscreen mode

5. reactive for Object State

<script setup>
import { reactive } from 'vue';

const user = reactive({ name: 'Alice', age: 25 });
function increaseAge() {
  user.age++;
}
</script>

<template>
  <p>{{ user.name }} is {{ user.age }} years old.</p>
  <button @click="increaseAge">Happy Birthday</button>
</template>
Enter fullscreen mode Exit fullscreen mode

6. Computed Property

<script setup>
import { ref, computed } from 'vue';

const count = ref(0);
const double = computed(() => count.value * 2);
</script>

<template>
  <p>Count: {{ count }}</p>
  <p>Double: {{ double }}</p>
  <button @click="count++">Increment</button>
</template>
Enter fullscreen mode Exit fullscreen mode

III. Lifecycle Hooks

7. onMounted Hook

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  console.log('Component mounted');
});
</script>
Enter fullscreen mode Exit fullscreen mode

8. watch Example

<script setup>
import { ref, watch } from 'vue';

const inputValue = ref('');
watch(inputValue, (newVal, oldVal) => {
  console.log(`Value changed from ${oldVal} to ${newVal}`);
});
</script>

<template>
  <input v-model="inputValue" placeholder="Type here" />
</template>
Enter fullscreen mode Exit fullscreen mode

IV. Templates & Directives

9. Conditional Rendering with v-if

<template>
  <p v-if="isLoggedIn">Welcome back!</p>
  <p v-else>Please log in.</p>
</template>

<script setup>
import { ref } from 'vue';

const isLoggedIn = ref(false);
</script>
Enter fullscreen mode Exit fullscreen mode

10. List Rendering with v-for

<template>
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
  </ul>
</template>

<script setup>
const items = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' }
];
</script>
Enter fullscreen mode Exit fullscreen mode

11. Custom Event Binding with v-on

<my-button @click="handleClick" />

<script setup>
function handleClick() {
  alert('Button clicked!');
}
</script>
Enter fullscreen mode Exit fullscreen mode

V. Composition API Advanced

12. provide and inject

// Provider.vue
<script setup>
import { provide } from 'vue';

const theme = 'dark';
provide('theme', theme);
</script>

// Consumer.vue
<script setup>
import { inject } from 'vue';

const theme = inject('theme', 'light');
</script>

<template>
  <p>The theme is: {{ theme }}</p>
</template>
Enter fullscreen mode Exit fullscreen mode

13. Custom Composable Hook

// useCounter.js
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  return { count, increment };
}
Enter fullscreen mode Exit fullscreen mode

VI. Forms and Two-way Binding

14. v-model on Input

<template>
  <input v-model="text" placeholder="Type something" />
  <p>You typed: {{ text }}</p>
</template>

<script setup>
import { ref } from 'vue';
const text = ref('');
</script>
Enter fullscreen mode Exit fullscreen mode

15. Custom v-model Binding in Component

<template>
  <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>

<script setup>
defineProps(['modelValue']);
</script>
Enter fullscreen mode Exit fullscreen mode

VII. Router Snippets

16. Programmatic Navigation

import { useRouter } from 'vue-router';

const router = useRouter();
function goHome() {
  router.push({ name: 'home' });
}
Enter fullscreen mode Exit fullscreen mode

17. Get Current Route Params

import { useRoute } from 'vue-router';

const route = useRoute();
const id = route.params.id;
Enter fullscreen mode Exit fullscreen mode

VIII. Vuex & Pinia State Management (Pinia example)

18. Define Pinia Store

import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({ name: 'John', age: 30 }),
  actions: { incrementAge() { this.age++ } }
});
Enter fullscreen mode Exit fullscreen mode

19. Using Pinia Store in Component

<script setup>
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
</script>

<template>
  <p>{{ userStore.name }} is {{ userStore.age }} years old.</p>
  <button @click="userStore.incrementAge">Happy Birthday</button>
</template>
Enter fullscreen mode Exit fullscreen mode

IX. Slots & Scoped Slots

20. Basic Default Slot

<template>
  <div class="card">
    <slot></slot>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

21. Scoped Slot Example

<template>
  <BaseList :items="items" v-slot="{ item }">
    <p>{{ item.name }}</p>
  </BaseList>
</template>
Enter fullscreen mode Exit fullscreen mode

X. Provide Common Utility Snippets

22. Debounce Input Using Watch

import { ref, watch } from 'vue';
import { debounce } from 'lodash';

const searchTerm = ref('');
const debouncedSearchTerm = ref('');

watch(searchTerm, debounce((val) => {
  debouncedSearchTerm.value = val;
}, 300));
Enter fullscreen mode Exit fullscreen mode

23. Fetch Data on Mounted

import { ref, onMounted } from 'vue';
import axios from 'axios';

const data = ref(null);

onMounted(async () => {
  const response = await axios.get('/api/data');
  data.value = response.data;
});
Enter fullscreen mode Exit fullscreen mode

XI. Transition & Animation

24. Simple Fade Transition

<template>
  <transition name="fade">
    <p v-if="show">Hello with fade</p>
  </transition>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
Enter fullscreen mode Exit fullscreen mode

XII. Common Patterns & Best Practices

25. Lazy Load Component

<script setup>
import { defineAsyncComponent } from 'vue';

const LazyComp = defineAsyncComponent(() => import('./LazyComponent.vue'));
</script>

<template>
  <LazyComp />
</template>
Enter fullscreen mode Exit fullscreen mode

26. Error Handling with try/catch in setup

import { ref } from 'vue';

const error = ref(null);

async function fetchData() {
  try {
    const data = await apiCall();
  } catch (e) {
    error.value = e.message;
  }
}
Enter fullscreen mode Exit fullscreen mode

XIII. Computed Watcher Simple Pattern

27. Watch with Computed Usage

import { ref, computed, watch } from 'vue';

const search = ref('');
const searchLength = computed(() => search.value.length);

watch(searchLength, (newVal) => {
  console.log(`Search length changed: ${newVal}`);
});
Enter fullscreen mode Exit fullscreen mode

XIV. Pagination Component

28. Basic Pagination Logic

<script setup>
import { ref, computed } from 'vue';

const currentPage = ref(1);
const itemsPerPage = 10;

const pagedItems = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  return items.value.slice(start, start + itemsPerPage);
});
</script>
Enter fullscreen mode Exit fullscreen mode

XV. Event Modifiers

29. Prevent Default and Stop Propagation

<button @click.prevent.stop="handleClick">Click me</button>
Enter fullscreen mode Exit fullscreen mode

XVI. Dynamic Classes and Styles

30. Object Syntax for Class Binding

<div :class="{ active: isActive, disabled: isDisabled }"></div>
Enter fullscreen mode Exit fullscreen mode

31. Inline Dynamic Styles

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Enter fullscreen mode Exit fullscreen mode

XVII. Router Link Active Classes

32. Highlight Active Nav Link

<router-link to="/" active-class="active-link">Home</router-link>
Enter fullscreen mode Exit fullscreen mode

XVIII. Provide/Inject with Reactivity

33. Reactive Provide/Inject

import { reactive, provide, inject } from 'vue';

const state = reactive({ count: 0 });

provide('state', state);

// In child
const state = inject('state');
Enter fullscreen mode Exit fullscreen mode

XIX. Watch for Deep Changes

34. Watching Deep Objects

watch(
  () => user,
  () => {
    console.log('User changed!');
  },
  { deep: true }
);
Enter fullscreen mode Exit fullscreen mode

XX. Template Ref Usage

35. Access DOM Element with ref

<script setup>
import { ref, onMounted } from 'vue';

const input = ref(null);

onMounted(() => {
  input.value.focus();
});
</script>

<template>
  <input ref="input" />
</template>
Enter fullscreen mode Exit fullscreen mode

XXI. Slots with Fallback Content

36. Default Slot Content

<slot>Default content if no slot provided</slot>
Enter fullscreen mode Exit fullscreen mode

XXII. Form Validation Using Watch

37. Simple Validation Example

import { ref, watch } from 'vue';

const email = ref('');
const isValid = ref(false);

watch(email, (newVal) => {
  isValid.value = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newVal);
});
Enter fullscreen mode Exit fullscreen mode

XXIII. Multiple Emits with Typescript

38. Defining Emits with Types

const emit = defineEmits<{
  (e: 'update', value: string): void;
  (e: 'delete'): void;
}>();
Enter fullscreen mode Exit fullscreen mode

XXIV. Dynamic Component Rendering

39. Render Based on Variable

<component :is="currentComponent" />
Enter fullscreen mode Exit fullscreen mode

XXV. Provide Scoped Slots Flexibility

40. Scoped Slots Passing Props

<slot :item="item"></slot>
Enter fullscreen mode Exit fullscreen mode

XXVI. Async Setup

41. Setup with Async/Await

<script setup>
import { ref } from 'vue';

const data = ref(null);

async function fetchData() {
  const res = await fetch('/api/data');
  data.value = await res.json();
}

fetchData();
</script>
Enter fullscreen mode Exit fullscreen mode

XXVII. WatchEffect Usage

42. Watching Reactive Dependencies

import { ref, watchEffect } from 'vue';

const count = ref(0);

watchEffect(() => {
  console.log(`Count is: ${count.value}`);
});
Enter fullscreen mode Exit fullscreen mode

XXVIII. Provide Default Slot Props

43. Default Values in Slots

<slot :user="user ?? {name:'Guest'}"></slot>
Enter fullscreen mode Exit fullscreen mode

XXIX. Template Directive Shorthands

44. Shorthand for v-bind & v-on

<!-- v-bind:href -->
<a :href="link">Link</a>

<!-- v-on:click -->
<button @click="handleClick">Click</button>
Enter fullscreen mode Exit fullscreen mode

XXX. Use key for List Performance

45. Key with Unique IDs

<li v-for="item in items" :key="item.id">{{ item.title }}</li>
Enter fullscreen mode Exit fullscreen mode

XXXI. Filters (Deprecated but still used)

46. Custom Filter Example

app.config.globalProperties.$filters = {
  capitalize(value) {
    if (!value) return '';
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
};
Enter fullscreen mode Exit fullscreen mode

XXXII. Provide Reusable Directive

47. v-focus Directive

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});
Enter fullscreen mode Exit fullscreen mode

XXXIII. Transition Modes

48. Transition with Mode

<transition name="fade" mode="out-in">
  <component :is="page" />
</transition>
Enter fullscreen mode Exit fullscreen mode

XXXIV. Provide UseSlots & UseAttrs

49. Access \$slots and \$attrs in script

import { useSlots, useAttrs } from 'vue';

const slots = useSlots();
const attrs = useAttrs();
Enter fullscreen mode Exit fullscreen mode

XXXV. Template Teleport

50. Teleport Element Outside Root

<teleport to="body">
  <div class="modal">Modal Content</div>
</teleport>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)