This content originally appeared on DEV Community and was authored by Software Developer
I. Basic Component Structures
1. Functional Component (Vue 3 setup syntax)
<script setup>
const greeting = 'Hello World';
</script>
<template>
<h1>{{ greeting }}</h1>
</template>
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>
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>
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>
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>
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>
III. Lifecycle Hooks
7. onMounted
Hook
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('Component mounted');
});
</script>
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>
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>
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>
11. Custom Event Binding with v-on
<my-button @click="handleClick" />
<script setup>
function handleClick() {
alert('Button clicked!');
}
</script>
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>
13. Custom Composable Hook
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment };
}
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>
15. Custom v-model
Binding in Component
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>
<script setup>
defineProps(['modelValue']);
</script>
VII. Router Snippets
16. Programmatic Navigation
import { useRouter } from 'vue-router';
const router = useRouter();
function goHome() {
router.push({ name: 'home' });
}
17. Get Current Route Params
import { useRoute } from 'vue-router';
const route = useRoute();
const id = route.params.id;
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++ } }
});
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>
IX. Slots & Scoped Slots
20. Basic Default Slot
<template>
<div class="card">
<slot></slot>
</div>
</template>
21. Scoped Slot Example
<template>
<BaseList :items="items" v-slot="{ item }">
<p>{{ item.name }}</p>
</BaseList>
</template>
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));
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;
});
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>
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>
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;
}
}
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}`);
});
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>
XV. Event Modifiers
29. Prevent Default and Stop Propagation
<button @click.prevent.stop="handleClick">Click me</button>
XVI. Dynamic Classes and Styles
30. Object Syntax for Class Binding
<div :class="{ active: isActive, disabled: isDisabled }"></div>
31. Inline Dynamic Styles
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
XVII. Router Link Active Classes
32. Highlight Active Nav Link
<router-link to="/" active-class="active-link">Home</router-link>
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');
XIX. Watch for Deep Changes
34. Watching Deep Objects
watch(
() => user,
() => {
console.log('User changed!');
},
{ deep: true }
);
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>
XXI. Slots with Fallback Content
36. Default Slot Content
<slot>Default content if no slot provided</slot>
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);
});
XXIII. Multiple Emits with Typescript
38. Defining Emits with Types
const emit = defineEmits<{
(e: 'update', value: string): void;
(e: 'delete'): void;
}>();
XXIV. Dynamic Component Rendering
39. Render Based on Variable
<component :is="currentComponent" />
XXV. Provide Scoped Slots Flexibility
40. Scoped Slots Passing Props
<slot :item="item"></slot>
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>
XXVII. WatchEffect Usage
42. Watching Reactive Dependencies
import { ref, watchEffect } from 'vue';
const count = ref(0);
watchEffect(() => {
console.log(`Count is: ${count.value}`);
});
XXVIII. Provide Default Slot Props
43. Default Values in Slots
<slot :user="user ?? {name:'Guest'}"></slot>
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>
XXX. Use key
for List Performance
45. Key with Unique IDs
<li v-for="item in items" :key="item.id">{{ item.title }}</li>
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);
}
};
XXXII. Provide Reusable Directive
47. v-focus Directive
app.directive('focus', {
mounted(el) {
el.focus();
}
});
XXXIII. Transition Modes
48. Transition with Mode
<transition name="fade" mode="out-in">
<component :is="page" />
</transition>
XXXIV. Provide UseSlots & UseAttrs
49. Access \$slots and \$attrs in script
import { useSlots, useAttrs } from 'vue';
const slots = useSlots();
const attrs = useAttrs();
XXXV. Template Teleport
50. Teleport Element Outside Root
<teleport to="body">
<div class="modal">Modal Content</div>
</teleport>
This content originally appeared on DEV Community and was authored by Software Developer