Vue Tutorial


Beginners To Experts


The site is under development.

VueJS

1.1 What is Vue.js?
Vue.js is a progressive JavaScript framework for building user interfaces.
It focuses on the view layer and is easy to integrate into projects.
Vue is designed to be incrementally adoptable.
<div id="app">{{ message }}</div>
<script src="https://unpkg.com/vue@3"></script>
<script>
const app = Vue.createApp({
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}).mount('#app')
</script>
      
1.2 Vue.js Features
Vue offers reactive data binding, components, directives, and a virtual DOM.
It allows easy composition of UI elements.
Vue's simplicity encourages fast development.
<template>
  <div>{{ greeting }}</div>
</template>
<script>
export default {
  data() {
    return {
      greeting: 'Vue is reactive!'
    }
  }
}
</script>
      
1.3 Setting up Vue.js
You can use Vue via CDN or npm packages.
The CDN method is easiest for small projects.
For large apps, Vue CLI or Vite are recommended.
<!-- CDN setup -->
<script src="https://unpkg.com/vue@3"></script>
<div id="app">{{ message }}</div>
      
1.4 Vue Instance
The Vue instance manages data and methods.
It connects the template with reactive properties.
It's created using Vue.createApp() in Vue 3.
<script>
const app = Vue.createApp({
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}).mount('#app')
</script>
      
1.5 Template Syntax
Vue uses a template syntax similar to HTML.
It supports interpolation and directives like v-bind and v-if.
Templates are compiled into render functions.
<div id="app">
  <p>{{ message }}</p>
  <button v-on:click="sayHi">Say Hi</button>
</div>

<script>
const app = Vue.createApp({
  data() { return { message: 'Hello!' } },
  methods: {
    sayHi() {
      alert(this.message)
    }
  }
}).mount('#app')
</script>
      
1.6 Data Binding
Vue enables reactive data binding to the DOM.
Changing data updates the view automatically.
This reduces the need for manual DOM manipulation.
<div id="app">
  <input v-model="name" placeholder="Enter name">
  <p>Hello, {{ name }}!</p>
</div>

<script>
const app = Vue.createApp({
  data() {
    return { name: '' }
  }
}).mount('#app')
</script>
      
1.7 Directives
Vue directives provide special reactive behavior in templates.
Examples include v-if, v-for, v-show, and v-bind.
They control conditional rendering, loops, and attribute binding.
<ul>
  <li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>

<script>
const app = Vue.createApp({
  data() {
    return {
      items: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' }
      ]
    }
  }
}).mount('#app')
</script>
      
1.8 Event Handling
Events like clicks and input changes can be handled with v-on or @ syntax.
Methods are defined in the Vue instance to respond to events.
This creates interactive UI components.
<button @click="increment">Clicked {{ count }} times</button>

<script>
const app = Vue.createApp({
  data() { return { count: 0 } },
  methods: {
    increment() {
      this.count++
    }
  }
}).mount('#app')
</script>
      
1.9 Computed Properties
Computed properties calculate and cache values based on reactive data.
They update only when dependencies change.
Computed are useful for complex data transformations.
<div>Full Name: {{ fullName }}</div>

<script>
const app = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    fullName() {
      return this.firstName + ' ' + this.lastName
    }
  }
}).mount('#app')
</script>
      
1.10 Lifecycle Hooks
Vue instances have lifecycle hooks like mounted, created, and updated.
These allow code to run at specific stages of the component life.
Useful for fetching data or cleaning up resources.
<script>
const app = Vue.createApp({
  data() { return { message: 'Hi' } },
  mounted() {
    console.log('Component mounted!')
  }
}).mount('#app')
</script>
      

2.1 What is a Component?
Components are reusable Vue instances with their own data and templates.
They help organize the UI into manageable pieces.
Components can be nested and composed.
<template>
  <div>Hello from a component!</div>
</template>

<script>
export default {
  name: 'MyComponent'
}
</script>
      
2.2 Registering Components
Components can be registered globally or locally within other components.
Global registration makes components available everywhere.
Local registration scopes components to a parent.
<script>
const MyComponent = {
  template: '<div>Hi!</div>'
}

Vue.createApp({})
  .component('my-component', MyComponent)
  .mount('#app')
</script>
      
2.3 Props
Props are custom attributes passed to components.
They allow data flow from parent to child components.
Props should be declared for validation.
<template>
  <div>Hello, {{ name }}!</div>
</template>

<script>
export default {
  props: ['name']
}
</script>
      
2.4 Emitting Events
Child components communicate with parents by emitting events.
Parents listen and respond to these events.
This enables two-way communication.
<template>
  <button @click="$emit('increment')">Increment</button>
</template>
      
2.5 Slots
Slots let you compose components with flexible content.
Default slots allow parent content to be injected into children.
Named slots provide multiple insertion points.
<template>
  <div>
    <slot>Default content</slot>
  </div>
</template>
      
2.6 Dynamic Components
Vue supports switching components dynamically with ``.
Useful for tabs or conditional rendering of multiple views.
Component name is reactive.
<component :is="currentTab"></component>

<script>
export default {
  data() {
    return { currentTab: 'home' }
  }
}
</script>
      
2.7 Async Components
Async components load only when needed, improving performance.
Useful for large applications with many components.
They are defined using dynamic imports.
<script>
const AsyncComp = () => import('./MyComponent.vue')

export default {
  components: {
    AsyncComp
  }
}
</script>
      
2.8 Provide/Inject
Provide/Inject allows passing data from ancestor to descendant without props.
Useful for plugin development and deeply nested components.
It breaks strict parent-child coupling.
<script>
export default {
  provide() {
    return { color: 'blue' }
  }
}
</script>

<script>
export default {
  inject: ['color']
}
</script>
      
2.9 Component Lifecycle
Components have their own lifecycle hooks like beforeMount and unmounted.
These hooks allow you to run code at specific component stages.
Useful for setup and cleanup.
<script>
export default {
  mounted() {
    console.log('Component mounted')
  },
  unmounted() {
    console.log('Component removed')
  }
}
</script>
      
2.10 Functional Components
Functional components are stateless and instanceless.
They render faster and are simpler.
Mainly used for presentational purposes.
<script>
export default {
  functional: true,
  render(h) {
    return h('div', 'I am functional!')
  }
}
</script>
      

3.1 What are Directives?
Directives are special tokens in the markup that tell Vue to do something reactive.
Examples include v-if, v-for, v-bind, and v-model.
They enhance HTML with dynamic behavior.
<div v-if="isVisible">Visible Content</div>
      
3.2 Conditional Rendering (v-if)
v-if conditionally renders elements based on expressions.
Elements are added or removed from the DOM accordingly.
Useful for showing/hiding content.
<div v-if="loggedIn">Welcome back!</div>
      
3.3 List Rendering (v-for)
v-for renders lists based on array or object data.
Each item in the list creates a DOM element.
Use a unique key for better performance.
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
      
3.4 Attribute Binding (v-bind)
v-bind dynamically binds HTML attributes to data.
Allows reactive updates to attributes like src, href, or class.
The shorthand is simply a colon (:).
<img :src="imageUrl" alt="Image">
      
3.5 Two-Way Binding (v-model)
v-model creates two-way binding between input elements and data.
Changes in the input update data and vice versa.
Commonly used in forms.
<input v-model="username" placeholder="Enter username">
<p>Hello, {{ username }}!</p>
      
3.6 Event Handling (v-on)
v-on listens to DOM events like clicks or input changes.
Can use shorthand @ for binding events.
Connects user interaction to Vue methods.
<button @click="submitForm">Submit</button>
      
3.7 Modifiers
Modifiers adjust event or directive behavior.
Examples include .stop, .prevent, and .once.
They help manage event flow and behavior.
<form @submit.prevent="onSubmit"></form>
      
3.8 Computed vs Watchers
Computed properties cache reactive calculations.
Watchers react to data changes and run functions.
Use computed for derived state, watchers for side effects.
<script>
computed: {
  reversed() {
    return this.text.split('').reverse().join('')
  }
},
watch: {
  text(newVal) {
    console.log('Text changed:', newVal)
  }
}
</script>
      
3.9 Dynamic Class & Style Binding
Vue can bind class and style dynamically based on data.
Useful for conditional styling and responsive UI.
Supports objects and arrays for multiple classes.
<div :class="{ active: isActive }" :style="{ color: textColor }">Styled Text</div>
      
3.10 Key Attribute
The key attribute helps Vue identify nodes for efficient updates.
Always use unique keys in v-for loops.
Prevents rendering bugs and improves performance.
<li v-for="item in list" :key="item.id">{{ item.name }}</li>
      

4.1 What are Methods?
Methods are functions defined in the Vue instance to handle actions.
They can be called from templates or event handlers.
Methods do not cache results.
<button @click="greet">Greet</button>

<script>
methods: {
  greet() {
    alert('Hello from method!')
  }
}
</script>
      
4.2 Computed Properties Overview
Computed properties automatically update when dependencies change.
They cache results for better performance.
Used for derived reactive data.
<div>Full Name: {{ fullName }}</div>

<script>
computed: {
  fullName() {
    return this.firstName + ' ' + this.lastName
  }
}
</script>
      
4.3 Difference: Methods vs Computed
Methods run on every call without caching.
Computed properties cache until dependencies change.
Computed is better for expensive operations.
<!-- Use computed for derived state -->
<div>Reversed: {{ reversedText }}</div>

<script>
computed: {
  reversedText() {
    return this.text.split('').reverse().join('')
  }
}
</script>
      
4.4 Using Watchers
Watchers observe data changes and trigger functions.
Useful for async or expensive operations on change.
Ideal for API calls based on input.
<script>
watch: {
  searchQuery(newVal) {
    this.fetchResults(newVal)
  }
}
</script>
      
4.5 Passing Arguments to Methods
Methods can accept arguments from event handlers or templates.
Useful for handling dynamic inputs.
Pass parameters via inline event syntax.
<button @click="sayHello('Vue')">Say Hello</button>

<script>
methods: {
  sayHello(name) {
    alert('Hello, ' + name)
  }
}
</script>
      
4.6 Method Binding with Parameters
You can bind methods to events with parameters using arrow functions.
Prevents immediate invocation.
<button @click="() => addItem(item)">Add</button>
      
4.7 Methods in Templates
Methods can be used inside templates for event handlers or interpolation.
However, avoid heavy logic inside templates.
<div>{{ formatDate(date) }}</div>

<script>
methods: {
  formatDate(d) {
    return new Date(d).toLocaleDateString()
  }
}
</script>
      
4.8 Computed Setters
Computed properties can have getters and setters.
Useful for two-way computed bindings.
Setter modifies underlying data.
<script>
computed: {
  fullName: {
    get() {
      return this.firstName + ' ' + this.lastName
    },
    set(value) {
      const names = value.split(' ')
      this.firstName = names[0]
      this.lastName = names[1]
    }
  }
}
</script>
      
4.9 Watch Deep and Immediate Options
Watchers can observe nested objects (deep) and run immediately (immediate).
Useful for complex state monitoring.
<script>
watch: {
  user: {
    handler(newVal) { console.log(newVal) },
    deep: true,
    immediate: true
  }
}
</script>
      
4.10 Debouncing with Watchers
Combine watchers with debounce to limit frequent function calls.
Improves performance with input or API calls.
<script>
watch: {
  searchQuery: _.debounce(function(newVal) {
    this.fetchResults(newVal)
  }, 500)
}
</script>
      

5.1 What is Vue Router?
Vue Router is the official routing library for Vue.js.
It enables SPA navigation without page reloads.
Defines routes to components.
<script>
import { createRouter, createWebHistory } from 'vue-router'
import Home from './components/Home.vue'

const routes = [
  { path: '/', component: Home }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
</script>
      
5.2 Setting up Vue Router
Install Vue Router via npm or CDN.
Register router in Vue app during creation.
Use <router-view> to display current route.
<script>
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
  .use(router)
  .mount('#app')
</script>
      
5.3 Defining Routes
Routes map URLs to components.
Can include nested routes and dynamic params.
Path matching controls navigation.
const routes = [
  { path: '/about', component: About },
  { path: '/user/:id', component: User }
]
      
5.4 Navigation Methods
Router provides programmatic navigation like push and replace.
Useful for redirects and navigation guards.
this.$router.push('/about')
      
5.5 Route Parameters
Dynamic segments in routes pass parameters to components.
Access via this.$route.params.
const userId = this.$route.params.id
      
5.6 Vuex State Management
Vuex is Vue’s official state management library.
Centralizes app state in a single store.
Supports mutations, actions, and getters.
import { createStore } from 'vuex'

const store = createStore({
  state() {
    return { count: 0 }
  },
  mutations: {
    increment(state) { state.count++ }
  }
})

export default store
      
5.7 Using Vuex in Components
Components access store state and dispatch actions.
Use computed properties for reactive state.
<script>
computed: {
  count() {
    return this.$store.state.count
  }
},
methods: {
  increment() {
    this.$store.commit('increment')
  }
}
</script>
      
5.8 Modules in Vuex
Vuex supports modularizing the store for scalability.
Modules have their own state, mutations, and actions.
Modules can be namespaced.
const moduleA = {
  state() { return { value: 1 } },
  mutations: { increment(state) { state.value++ } }
}
      
5.9 Alternatives to Vuex
Pinia is a lightweight alternative to Vuex for state management.
Provides simpler API with Vue 3 support.
Good for smaller or modular apps.
import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => ({ count: 0 }),
  actions: {
    increment() { this.count++ }
  }
})
      
5.10 Navigation Guards
Guards control access during route changes.
Can allow, redirect, or cancel navigation.
Useful for authentication and permissions.
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})
      

6.1 Handling Forms in Vue
Vue provides two-way binding with v-model for form inputs.
Forms are reactive and update the data model instantly.
Supports text, checkbox, radio, and select inputs.
<input v-model="username" placeholder="Enter username">
<p>Username: {{ username }}</p>
      
6.2 Input Bindings
v-model binds different input types with slight syntax variations.
For checkbox and radio, binding values differ.
Enables easy synchronization.
<input type="checkbox" v-model="isChecked">
<input type="radio" v-model="picked" value="A">
      
6.3 Modifiers in Forms
Modifiers like .lazy, .trim, and .number adjust v-model behavior.
.lazy updates on change, .trim trims whitespace, .number casts to number.
Useful for form validation.
<input v-model.lazy="text">
<input v-model.trim="text">
<input v-model.number="age">
      
6.4 Form Submission
Use v-on:submit.prevent to handle form submissions.
Prevents default page reload behavior.
Calls a method to process the form.
<form @submit.prevent="submitForm">
  <input v-model="email">
  <button type="submit">Submit</button>
</form>
      
6.5 Basic Validation
Vue does not have built-in validation but integrates with libraries.
Simple checks can be implemented in methods.
Validates input before submission.
<script>
methods: {
  submitForm() {
    if (!this.email) alert('Email required')
    else alert('Form submitted')
  }
}
</script>
      
6.6 Using Vuelidate
Vuelidate is a lightweight validation library for Vue.js.
Allows declarative validation rules.
Supports reactive validation states.
<script>
import { required, email } from '@vuelidate/validators'
export default {
  validations: {
    email: { required, email }
  }
}
</script>
      
6.7 Using Vue Formulate
Vue Formulate simplifies forms and validation setup.
Provides form inputs, validation, and error messages out of the box.
Highly customizable.
<FormulateInput
  name="email"
  label="Email"
  type="email"
  validation="required|email"
/>
      
6.8 Custom Validation
You can create your own validation rules.
Rules can be functions returning boolean or messages.
Integrates with Vue's reactive system.
<script>
methods: {
  validateAge(value) {
    return value >= 18 || 'Must be 18 or older'
  }
}
</script>
      
6.9 Showing Validation Errors
Display validation errors conditionally in templates.
Use reactive variables to show messages.
Improves user experience.
<span v-if="error">{{ error }}</span>
      
6.10 Form Reset
Reset form fields by resetting bound data.
Can be done in methods after submission or cancel.
Keeps UI in sync.
<script>
methods: {
  resetForm() {
    this.username = ''
    this.email = ''
  }
}
</script>
      

7.1 What are Custom Directives?
Custom directives let you add low-level DOM manipulations.
Used when built-in directives are insufficient.
Defined with hooks like mounted and updated.
<script>
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})
</script>
      
7.2 Registering Custom Directives
Register directives globally or locally in components.
Global registration available in app instance.
Local registration within component's directives option.
<script>
app.directive('highlight', {
  beforeMount(el) {
    el.style.backgroundColor = 'yellow'
  }
})
</script>
      
7.3 Directive Lifecycle Hooks
Directives have hooks: created, beforeMount, mounted, beforeUpdate, updated, unmounted.
Use hooks to manipulate DOM at different stages.
Useful for cleanup and updates.
<script>
app.directive('tooltip', {
  mounted(el) {
    el.setAttribute('title', 'Tooltip text')
  },
  unmounted(el) {
    // cleanup
  }
})
</script>
      
7.4 Directive Arguments & Modifiers
Arguments and modifiers customize directives behavior.
Arguments provide data, modifiers toggle options.
<div v-highlight:color.red>Colored Background</div>
<script>
app.directive('highlight', {
  beforeMount(el, binding) {
    el.style.backgroundColor = binding.arg || 'blue'
    if (binding.modifiers.red) el.style.color = 'red'
  }
})
</script>
      
7.5 Creating Plugins
Plugins add global functionality to Vue apps.
Can add components, directives, or methods globally.
Created as an install function.
<script>
const MyPlugin = {
  install(app) {
    app.config.globalProperties.$myMethod = () => alert('Plugin method')
  }
}
app.use(MyPlugin)
</script>
      
7.6 Using Plugins
After installation, plugin features are accessible app-wide.
Access global properties via this or app.config.globalProperties.
Simplifies app-wide utilities.
<script>
export default {
  mounted() {
    this.$myMethod()
  }
}
</script>
      
7.7 Plugin Options
Plugins can accept options during installation for configuration.
Enhances flexibility and reuse.
<script>
const MyPlugin = {
  install(app, options) {
    console.log('Options:', options)
  }
}
app.use(MyPlugin, { debug: true })
</script>
      
7.8 Writing Reusable Plugins
Write plugins that can register components, directives, or mixins.
Makes features portable.
<script>
const MyPlugin = {
  install(app) {
    app.component('MyButton', { /* component code */ })
    app.directive('focus', { /* directive code */ })
  }
}
</script>
      
7.9 Publishing Plugins
Plugins can be published as npm packages.
Provide clear documentation and versioning.
Enables community sharing.
npm publish
      
7.10 Using Third-party Plugins
Many Vue plugins exist for routing, validation, UI components, and more.
Install via npm and use app.use().
import VueToast from 'vue-toastification'
app.use(VueToast)
      

8.1 Introduction to Composition API
The Composition API offers a flexible way to organize component logic.
It uses setup() function to declare reactive state and methods.
Designed for better code reuse.
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
      
8.2 Reactive State with ref
ref creates reactive primitive values.
Use .value to access or mutate data.
Automatically tracks dependencies.
<script setup>
import { ref } from 'vue'
const message = ref('Hello!')
message.value = 'Hi!'
</script>
      
8.3 Reactive Objects with reactive
reactive wraps objects to make them reactive.
Changes to properties trigger updates.
Unlike ref, no need for .value access.
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0 })
state.count++
</script>
      
8.4 Computed with Composition API
Computed can be used to create derived reactive values.
Import computed from vue and define inside setup.
Useful for complex calculations.
<script setup>
import { ref, computed } from 'vue'
const first = ref('John')
const last = ref('Doe')
const fullName = computed(() => first.value + ' ' + last.value)
</script>
      
8.5 Watchers with Composition API
watch tracks reactive sources and executes callbacks on change.
Used for side effects and async operations.
Imported from vue.
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newVal, oldVal) => {
  console.log('Count changed:', newVal)
})
</script>
      
8.6 Lifecycle Hooks in Composition API
Lifecycle hooks are imported and called inside setup.
Examples include onMounted, onUnmounted, and onUpdated.
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
  console.log('Component mounted')
})
</script>
      
8.7 Provide and Inject in Composition API
Provide/inject can be used via functions inside setup.
Allows passing data deeply without props.
<script setup>
import { provide, inject } from 'vue'
provide('color', 'blue')
const color = inject('color')
</script>
      
8.8 Template Refs
Template refs give direct access to DOM elements or child components.
Defined using ref attribute and accessed in setup.
<template>
  <input ref="inputEl">
</template>

<script setup>
import { ref, onMounted } from 'vue'
const inputEl = ref(null)
onMounted(() => inputEl.value.focus())
</script>
      
8.9 Using Emits
Emits declare events emitted by a component in setup.
Use defineEmits to specify emitted events.
<script setup>
const emit = defineEmits(['increment'])
function handleClick() {
  emit('increment')
}
</script>
      
8.10 Composables
Composables are reusable functions encapsulating reactive logic.
Promote code reuse and cleaner components.
<script>
import { ref } from 'vue'

export function useCounter() {
  const count = ref(0)
  function increment() {
    count.value++
  }
  return { count, increment }
}
</script>
      

9.1 Introduction to Testing
Testing ensures your Vue app works as expected.
Includes unit, integration, and end-to-end tests.
Helps catch bugs early.
<!-- Jest is popular for unit tests -->
      
9.2 Unit Testing with Vue Test Utils
Vue Test Utils provides utilities to mount components and inspect output.
Works with Jest or Mocha.
Test component behavior in isolation.
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

test('renders message', () => {
  const wrapper = mount(MyComponent)
  expect(wrapper.text()).toContain('Hello')
})
      
9.3 Writing Test Cases
Test cases describe expected behavior of components or functions.
Use assertions to verify outcomes.
Keep tests clear and focused.
test('button click increments count', () => {
  const wrapper = mount(Counter)
  wrapper.find('button').trigger('click')
  expect(wrapper.vm.count).toBe(1)
})
      
9.4 Snapshot Testing
Snapshots capture component output structure.
Useful to detect unexpected UI changes.
Jest supports snapshot testing.
expect(wrapper.html()).toMatchSnapshot()
      
9.5 End-to-End Testing with Cypress
Cypress automates browser testing for entire user flows.
Tests real user interactions in a browser.
Good for integration and acceptance tests.
describe('Login flow', () => {
  it('logs in successfully', () => {
    cy.visit('/login')
    cy.get('input').type('user')
    cy.get('button').click()
    cy.url().should('include', '/dashboard')
  })
})
      
9.6 Debugging Vue Apps
Vue Devtools browser extension helps inspect component state and events.
Console logs and breakpoints aid debugging.
Essential for efficient development.
console.log(this.someData)
      
9.7 Handling Errors Gracefully
Use error boundaries or global error handlers.
Provide fallback UI to avoid crashes.
app.config.errorHandler = (err, vm, info) => {
  console.error(err, info)
}
      
9.8 Mocking Dependencies
Mock APIs or modules during testing.
Isolates unit tests from external dependencies.
jest.mock('axios')
      
9.9 Performance Profiling
Measure component render times and memory usage.
Optimize slow components.
Vue.config.performance = true
      
9.10 Testing Best Practices
Write small, fast, independent tests.
Keep tests deterministic and repeatable.
Use descriptive test names.
test('does something', () => {
  expect(true).toBe(true)
})
      

10.1 Understanding Performance
Performance is about speed and responsiveness.
Slow apps frustrate users.
Vue provides tools to measure and improve performance.
Vue.config.performance = true
      
10.2 Lazy Loading Components
Load components only when needed using dynamic import.
Reduces initial bundle size.
const AsyncComp = () => import('./AsyncComp.vue')
      
10.3 Virtual Scrolling
Render only visible portions of large lists.
Improves rendering performance.
<virtual-list :items="bigList"></virtual-list>
      
10.4 Debounce & Throttle
Limit how often functions run during rapid events.
Useful for scroll or input events.
methods: {
  onScroll: _.throttle(function() {
    console.log('Scrolled')
  }, 200)
}
      
10.5 Use Key Attribute Wisely
Use unique keys to help Vue track DOM elements efficiently.
Prevent unnecessary re-renders.
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
      
10.6 Optimize Computed Properties
Avoid heavy computations inside computed that run too frequently.
Use caching and memoization.
computed: {
  filteredList() {
    return this.list.filter(item => item.active)
  }
}
      
10.7 Avoid Watchers if Possible
Computed properties are preferred over watchers for derived state.
Watchers can cause unnecessary side effects.
computed: {
  total() {
    return this.items.reduce((sum, i) => sum + i.price, 0)
  }
}
      
10.8 Server-Side Rendering
SSR renders Vue apps on the server for faster load and SEO.
Requires special setup.
npm install vue-server-renderer
      
10.9 Using Web Workers
Offload heavy computations to web workers to keep UI responsive.
Use worker threads or libraries.
const worker = new Worker('worker.js')
      
10.10 Performance Tools
Use Vue Devtools, Chrome Devtools, and Lighthouse to profile performance.
Identify bottlenecks.
Vue.config.devtools = true
      

11.1 Async Components
Components loaded only when needed to reduce bundle size.
const AsyncComp = () => import('./AsyncComp.vue')
      
11.2 Dynamic & Async Component Usage
Use <component :is="componentName"> for dynamic rendering.
<component :is="currentComponent"></component>
      
11.3 Render Functions
Use render functions for fine control over output.
Written in JavaScript instead of templates.
render() {
  return h('div', this.message)
}
      
11.4 Scoped Slots
Pass data from child to parent slots.
Enhances component flexibility.
<slot :user="user"></slot>
      
11.5 Functional Components
Stateless, faster components without lifecycle.
Defined as simple functions.
export default {
  functional: true,
  render(h, ctx) {
    return h('div', ctx.props.text)
  }
}
      
11.6 Mixins
Reuse component logic across components.
Use with caution to avoid conflicts.
const myMixin = {
  created() {
    console.log('Mixin created')
  }
}
      
11.7 Custom Events & $emit
Components communicate by emitting events.
Parents listen for events.
this.$emit('customEvent', payload)
      
11.8 Provide/Inject API
Share data across nested components without props.
Useful for plugins or deep component trees.
provide() { return { color: 'red' } }
inject: ['color']
      
11.9 Dynamic Async Components with Suspense
Handle async components with fallback loading UI.
<Suspense>
  <template #default>
    <AsyncComp />
  </template>
  <template #fallback>
    Loading...
  </template>
</Suspense>
      
11.10 Teleport
Render a component's DOM outside its parent.
Useful for modals or tooltips.
<teleport to="body">
  <div class="modal">Modal Content</div>
</teleport>
      

12.1 Introduction to Transitions
Vue supports CSS and JavaScript transitions.
Helps animate elements entering/leaving DOM.
<transition name="fade">
  <div v-if="show">Fade me</div>
</transition>
      
12.2 Transition Classes
Vue adds classes like .fade-enter-active automatically.
Use CSS to style transitions.
.fade-enter-active { transition: opacity 0.5s; }
.fade-enter-from { opacity: 0; }
.fade-enter-to { opacity: 1; }
      
12.3 JavaScript Hooks
Control transitions with JS hooks for fine control.
Hooks: beforeEnter, enter, afterEnter, etc.
<transition
  @before-enter="beforeEnter"
  @enter="enter"
  @after-enter="afterEnter">
</transition>
      
12.4 List Transitions (v-for)
Animate items in lists during add/remove.
Use <transition-group> for list animations.
<transition-group name="list">
  <li v-for="item in items" :key="item.id">{{ item.name }}</li>
</transition-group>
      
12.5 Using Animate.css with Vue
Integrate popular CSS animation libraries.
Add animation classes in transition hooks.
<transition
  enter-active-class="animate__animated animate__bounce">
  <div v-if="show">Bounce!</div>
</transition>
      
12.6 Custom Animation with GSAP
Use GSAP for complex JavaScript animations.
Control timelines in hooks.
import { gsap } from 'gsap'

methods: {
  enter(el, done) {
    gsap.fromTo(el, {opacity: 0}, {opacity: 1, duration: 1, onComplete: done})
  }
}
      
12.7 Staggered Transitions
Animate multiple elements with delay.
Use CSS or JS to stagger timings.
.list-enter-active > * {
  transition-delay: calc(var(--index) * 100ms);
}
      
12.8 Transition Modes
Modes control simultaneous or sequential transitions.
Modes: 'in-out' and 'out-in'.
<transition mode="out-in"></transition>
      
12.9 Animating Route Changes
Use transition with router-view.
Animate page navigation.
<transition name="fade">
  <router-view />
</transition>
      
12.10 Performance Tips
Keep animations simple for better performance.
Avoid layout thrashing.
Use transform and opacity properties.
.fade-enter-active { transition: transform 0.3s ease; }
      

13.1 What is Internationalization?
Support multiple languages in your app.
Enables global reach.
npm install vue-i18n
      
13.2 Setting Up Vue i18n
Import and configure locale messages.
Create i18n instance.
import { createI18n } from 'vue-i18n'

const messages = {
  en: { welcome: 'Welcome' },
  fr: { welcome: 'Bienvenue' }
}

const i18n = createI18n({
  locale: 'en',
  messages,
})

app.use(i18n)
      
13.3 Using $t for Translation
Use $t function in templates and scripts.
<p>{{ $t('welcome') }}</p>
      
13.4 Changing Locale
Change language dynamically by updating locale.
this.$i18n.locale = 'fr'
      
13.5 Pluralization
Handle plural forms in translations.
Use plural rules in messages.
messages: {
  en: { apple: 'apple | apples' }
}
      
13.6 Date & Number Formatting
Format dates and numbers per locale.
Built-in Intl API support.
this.$d(new Date(), 'short')
      
13.7 Lazy Loading Language Packs
Load locale data on demand to reduce bundle.
Improves app performance.
import('locales/fr.json').then(...)
      
13.8 Fallback Locale
Define fallback language if key missing.
Prevents untranslated text.
fallbackLocale: 'en'
      
13.9 Custom Directives for i18n
Create directives to handle translations.
Example: v-t directive.
<div v-t="'welcome'"></div>
      
13.10 Integrating with Vue Router
Manage routes per locale.
Redirect based on user language.
router.beforeEach((to, from, next) => {
  const lang = to.params.lang || 'en'
  i18n.locale = lang
  next()
})
      

14.1 What is SSR?
Server-side rendering pre-renders app HTML on the server.
Improves SEO and load speed.
npm install vue-server-renderer
      
14.2 Setting up SSR
Use Vue SSR API or frameworks like Nuxt.js.
Render app to string on server.
import { renderToString } from '@vue/server-renderer'
const app = createSSRApp(App)
const html = await renderToString(app)
      
14.3 Hydration
Client-side Vue takes over server-rendered HTML.
Keeps app interactive.
createApp(App).mount('#app')
      
14.4 Benefits of SSR
Faster first paint.
Better SEO.
Improved social media sharing.
console.log('SSR benefits')
      
14.5 SSR with Nuxt.js
Nuxt simplifies SSR setup.
Provides file-based routing and data fetching.
npx create-nuxt-app my-nuxt-app
      
14.6 Data Fetching in SSR
Fetch data on server before rendering.
Use asyncData or fetch hooks.
export default {
  asyncData() {
    return fetchData()
  }
}
      
14.7 Handling State Transfer
Transfer state from server to client to avoid duplicate fetch.
Use window.__INITIAL_STATE__.
app.$store.replaceState(window.__INITIAL_STATE__)
      
14.8 Caching Strategies
Cache rendered pages or components.
Improve SSR performance.
const cache = new LRUCache()
      
14.9 SSR Security Considerations
Sanitize user input.
Prevent XSS attacks.
app.use(helmet())
      
14.10 Debugging SSR
Use server logs and source maps.
Debug hydration mismatches.
console.error('SSR error', error)
      

15.1 Vue CLI
Official CLI tool for scaffolding Vue projects.
Provides presets and plugins.
npm install -g @vue/cli
vue create my-project
      
15.2 Vue Router
Official router for Vue.js.
Supports nested routes and navigation guards.
import { createRouter, createWebHistory } from 'vue-router'

const routes = [{ path: '/', component: Home }]
const router = createRouter({ history: createWebHistory(), routes })
app.use(router)
      
15.3 Vuex
State management pattern for Vue apps.
Centralizes app state.
import { createStore } from 'vuex'

const store = createStore({
  state() { return { count: 0 } },
  mutations: { increment(state) { state.count++ } }
})
app.use(store)
      
15.4 Vue Devtools
Browser extension for debugging Vue apps.
Inspect components, events, Vuex state.
Install from browser store
      
15.5 Vue Test Utils
Utilities for testing Vue components.
Supports unit testing.
import { mount } from '@vue/test-utils'
      
15.6 Vite
Modern build tool for Vue with fast hot reload.
Simplifies development.
npm init vite@latest my-vue-app -- --template vue
      
15.7 ESLint & Prettier
Tools for code quality and formatting.
Integrate with Vue CLI.
npm install eslint prettier --save-dev
      
15.8 Storybook
UI component explorer.
Develop and test components in isolation.
npx sb init
      
15.9 Nuxt.js
Framework for SSR and static site generation.
Enhances Vue with conventions.
npm install nuxt
      
15.10 Pinia
Next-gen state management library.
Lightweight and modular alternative to Vuex.
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
      

16.1 Reactive & Ref Deep Dive
Understand reactive objects and refs for reactivity.
import { reactive, ref } from 'vue'

const state = reactive({ count: 0 })
const number = ref(10)
      
16.2 Computed Properties with Composition API
Create reactive computed values.
import { computed } from 'vue'

const double = computed(() => state.count * 2)
      
16.3 Watchers in Composition API
Watch reactive values and trigger side effects.
import { watch } from 'vue'

watch(() => state.count, (newVal, oldVal) => {
  console.log(newVal, oldVal)
})
      
16.4 Lifecycle Hooks in Setup
Use lifecycle hooks inside setup function.
import { onMounted } from 'vue'

onMounted(() => {
  console.log('Component mounted')
})
      
16.5 Provide/Inject with Composition API
Share reactive data across components.
import { provide, inject } from 'vue'

provide('key', reactiveData)
const data = inject('key')
      
16.6 Using Template Refs
Access DOM elements reactively.
import { ref, onMounted } from 'vue'

const inputRef = ref(null)

onMounted(() => {
  inputRef.value.focus()
})
      
16.7 Custom Composition Functions
Extract reusable logic into functions.
function useCounter() {
  const count = ref(0)
  const increment = () => count.value++
  return { count, increment }
}
      
16.8 Reactive vs. Ref
Reactive for objects, ref for primitives.
Understand when to use each.
const obj = reactive({ a: 1 })
const num = ref(1)
      
16.9 Async Setup & Suspense
Handle async data fetching in setup.
Combine with Suspense component.
setup: async () => {
  const data = await fetchData()
  return { data }
}
      
16.10 TypeScript with Composition API
Strong typing in Composition API.
Use interfaces and generics.
import { ref } from 'vue'

const message = ref<string>('Hello')
      

17.1 Vuex Modules
Split store into modules for scalability.
const moduleA = {
  state: { count: 0 },
  mutations: { increment(state) { state.count++ } }
}
const store = createStore({
  modules: { a: moduleA }
})
      
17.2 Namespaced Modules
Avoid naming conflicts with namespaces.
const moduleB = {
  namespaced: true,
  state: { value: 10 }
}
      
17.3 Vuex Actions with Async
Handle async logic in actions.
actions: {
  async fetchData({ commit }) {
    const data = await api.getData()
    commit('setData', data)
  }
}
      
17.4 Vuex Getters
Derive state with getters.
getters: {
  doubleCount(state) {
    return state.count * 2
  }
}
      
17.5 Committing Mutations
Mutations update state synchronously.
store.commit('increment')
      
17.6 Dispatching Actions
Use dispatch to call actions.
store.dispatch('fetchData')
      
17.7 Using mapState and mapActions
Helpers to map store state and actions.
import { mapState, mapActions } from 'vuex'

computed: {
  ...mapState(['count'])
},
methods: {
  ...mapActions(['increment'])
}
      
17.8 Plugins in Vuex
Extend store functionality with plugins.
const myPlugin = store => {
  store.subscribe((mutation, state) => {
    console.log(mutation.type)
  })
}
      
17.9 Strict Mode
Enable strict mode to catch state mutations outside mutations.
const store = createStore({ strict: true })
      
17.10 Testing Vuex Stores
Test state, mutations, actions in isolation.
test('mutation increments count', () => {
  const state = { count: 0 }
  mutations.increment(state)
  expect(state.count).toBe(1)
})
      

18.1 Dynamic Route Matching
Use params in routes for dynamic URLs.
const routes = [
  { path: '/user/:id', component: User }
]
      
18.2 Nested Routes
Create child routes for nested views.
const routes = [
  { path: '/parent', component: Parent,
    children: [
      { path: 'child', component: Child }
    ]
  }
]
      
18.3 Named Views
Render multiple views in same route.
const routes = [
  { path: '/',
    components: {
      default: DefaultComp,
      sidebar: SidebarComp
    }
  }
]
      
18.4 Navigation Guards
Control access to routes.
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) next('/login')
  else next()
})
      
18.5 Lazy Loading Routes
Load route components on demand.
const routes = [
  { path: '/about', component: () => import('./About.vue') }
]
      
18.6 Scroll Behavior
Customize scroll on route navigation.
const router = createRouter({
  scrollBehavior() {
    return { top: 0 }
  }
})
      
18.7 Route Meta Fields
Store custom data on routes.
Useful for guards and UI.
{ path: '/admin', meta: { requiresAuth: true } }
      
18.8 Programmatic Navigation
Navigate using router methods.
this.$router.push('/home')
      
18.9 Route Props
Pass params as props to components.
{ path: '/user/:id', props: true }
      
18.10 Navigation Failures Handling
Handle navigation errors gracefully.
this.$router.push('/home').catch(err => {})
      

19.1 Using Vuex in Composition API
Access Vuex store inside setup.
import { useStore } from 'vuex'

setup() {
  const store = useStore()
  store.commit('increment')
}
      
19.2 Using Router in Composition API
Access router and route objects.
import { useRouter, useRoute } from 'vue-router'

setup() {
  const router = useRouter()
  const route = useRoute()
}
      
19.3 Navigation in Setup
Programmatic navigation using router.
router.push('/dashboard')
      
19.4 Reactive Route Params
Watch route params reactively.
watch(() => route.params.id, (newId) => {
  fetchData(newId)
})
      
19.5 Vuex Actions with Composition API
Dispatch Vuex actions inside setup.
store.dispatch('fetchData')
      
19.6 Mapping Vuex State
Use computed to map Vuex state.
const count = computed(() => store.state.count)
      
19.7 Handling Route Guards
Use router.beforeEach to guard routes.
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) next('/login')
  else next()
})
      
19.8 Async Data Fetching on Route Change
Fetch data when route changes.
watch(() => route.params.id, fetchData)
      
19.9 Using Suspense with Router
Show fallback UI during async route components.
<Suspense><router-view /></Suspense>
      
19.10 Testing Components with Vuex & Router
Mock store and router for unit tests.
const store = createStore(...)
const router = createRouter(...)
mount(Component, { global: { plugins: [store, router] } })
      

20.1 Production Build
Create optimized production bundle.
npm run build
      
20.2 Environment Variables
Use .env files to store configs.
VUE_APP_API_URL=https://api.example.com
      
20.3 Deploying to Netlify
Easy static site deployment.
git push origin main
Connect repo in Netlify dashboard
      
20.4 Deploying to Vercel
Supports static and SSR.
vercel --prod
      
20.5 Performance Audits
Use Lighthouse to audit app.
Fix performance issues.
lighthouse https://myapp.com
      
20.6 Code Splitting
Split code for faster loading.
const AsyncComp = () => import('./AsyncComp.vue')
      
20.7 Lazy Loading Routes & Components
Load only necessary code.
const routes = [{ path: '/about', component: () => import('./About.vue') }]
      
20.8 SEO Optimization
Use SSR or prerendering.
Add meta tags.

      
20.9 Security Best Practices
Sanitize inputs and avoid XSS.
Use Content Security Policy.

      
20.10 Monitoring & Analytics
Integrate tools like Google Analytics.
Track user behavior.
gtag('config', 'GA_TRACKING_ID')
      

21.1 Unit Testing Basics
Test individual components and functions.
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

const wrapper = mount(MyComponent)
expect(wrapper.text()).toContain('Hello')
      
21.2 Using Jest with Vue
Popular test runner for Vue apps.
npm install --save-dev jest vue-jest @vue/test-utils
      
21.3 Snapshot Testing
Save component output for future comparison.
expect(wrapper.html()).toMatchSnapshot()
      
21.4 Mocking Vuex Store
Isolate tests by mocking store.
import { createStore } from 'vuex'
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

const store = createStore({ state: { count: 1 } })
const wrapper = mount(MyComponent, { global: { plugins: [store] } })
expect(wrapper.text()).toContain('1')
      
21.5 Testing Router Navigation
Mock router for navigation tests.
import { createRouter, createWebHistory } from 'vue-router'
import { mount } from '@vue/test-utils'

const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/', component: {} }]
})

const wrapper = mount(MyComponent, { global: { plugins: [router] } })
router.push('/')
await router.isReady()
expect(wrapper.html()).toContain('Welcome')
      
21.6 Debugging Tools
Use Vue Devtools and console logs.
console.log(this.$data)
      
21.7 Error Handling
Use errorCaptured lifecycle hook.
export default {
  errorCaptured(err, vm, info) {
    console.error('Error:', err)
  }
}
      
21.8 Handling Async Tests
Use async/await in test functions.
test('fetches data', async () => {
  await wrapper.vm.fetchData()
  expect(wrapper.text()).toContain('Data loaded')
})
      
21.9 End-to-End Testing
Use Cypress or Selenium for UI tests.
npx cypress open
      
21.10 Performance Profiling
Use browser devtools performance tab.
Optimize slow components.
performance.mark('start')
// Run Vue component render or logic here
performance.mark('end')
performance.measure('myMeasure', 'start', 'end')
      

22.1 Introduction to State Management
Manage app state beyond components.
import { reactive } from 'vue'

const state = reactive({ count: 0 })
      
22.2 Pinia
Modern, lightweight Vue state management.
import { createPinia, defineStore } from 'pinia'

const useStore = defineStore('main', {
  state: () => ({ count: 0 }),
  actions: {
    increment() { this.count++ }
  }
})

app.use(createPinia())
      
22.3 Using Vue Observable
Make reactive objects without Vuex.
import { reactive } from 'vue'

const state = reactive({ value: 0 })
      
22.4 Local Storage for State
Persist state between sessions.
localStorage.setItem('count', state.count)
state.count = Number(localStorage.getItem('count')) || 0
      
22.5 Using provide/inject for State
Pass reactive state without Vuex.
import { provide, inject, reactive } from 'vue'

const state = reactive({ count: 0 })
provide('state', state)

// In child component
const state = inject('state')
      
22.6 Comparing Vuex vs Pinia
Pros and cons of each.
console.log('Pinia is modular, simpler; Vuex has bigger community and plugins')
      
22.7 MobX with Vue
Use MobX for reactivity.
import { observable } from 'mobx'

const state = observable({ count: 0 })
      
22.8 Zustand & Other Alternatives
Other state libraries compatible.
import create from 'zustand'

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}))
      
22.9 Best Practices for State Management
Keep state minimal and normalized.
state: {
  users: [],
  posts: []
}
      
22.10 Debugging State
Use devtools and logging.
console.log(state)
      

23.1 Composable Functions
Reusable logic encapsulated in functions.
import { ref } from 'vue'

function useToggle() {
  const isOn = ref(false)
  function toggle() { isOn.value = !isOn.value }
  return { isOn, toggle }
}
      
23.2 Separation of Concerns
Keep logic separate from UI.
const { data, fetchData } = useApi()
      
23.3 Reusing Reactive State
Share reactive state across components.
import { reactive } from 'vue'

const sharedState = reactive({ count: 0 })
      
23.4 Use of Watchers & Effects
React to changes declaratively.
import { watch } from 'vue'

watch(count, (val) => {
  console.log('Count changed:', val)
})
      
23.5 Handling Side Effects
Manage effects outside template.
import { onMounted } from 'vue'

onMounted(() => {
  fetchData()
})
      
23.6 Providing & Injecting Composables
Pass composables down the component tree.
import { provide } from 'vue'

provide('auth', useAuth())
      
23.7 Async Composables
Use async/await inside composables.
import { ref } from 'vue'

async function useData() {
  const data = ref(null)
  data.value = await fetchApi()
  return { data }
}
      
23.8 Error Handling in Composables
Handle errors gracefully.
try {
  await fetch()
} catch(e) {
  console.error(e)
}
      
23.9 Testing Composables
Test composables independently.
import { nextTick } from 'vue'
// Write unit tests that call composables and assert outputs
      
23.10 Documentation & Naming
Write clear composable APIs.
Use consistent naming.
function useUser() {
  // ...
}
      

24.1 What are Vue Plugins?
Extend Vue functionality globally.
export default {
  install(app) {
    // Plugin code here
  }
}
      
24.2 Creating a Simple Plugin
Add global methods or properties.
export default {
  install(app) {
    app.config.globalProperties.$myMethod = () => console.log('Hello from plugin')
  }
}
      
24.3 Using Plugins in Vue
Register plugins via app.use()
import MyPlugin from './MyPlugin'
app.use(MyPlugin)
      
24.4 Plugin Options
Pass options during installation.
app.use(MyPlugin, { option: true })
      
24.5 Plugin Lifecycle Hooks
Use hooks inside plugins.
app.mixin({
  mounted() {
    console.log('Component mounted')
  }
})
      
24.6 Global Components in Plugins
Register components globally.
app.component('MyButton', MyButton)
      
24.7 Directives in Plugins
Register custom directives.
app.directive('focus', {
  mounted(el) { el.focus() }
})
      
24.8 Composables in Plugins
Export reusable composables.
export function usePluginFeature() {
  // composable logic
}
      
24.9 Publishing Plugins
Publish on npm for reuse.
npm publish
      
24.10 Best Practices
Keep plugins small and focused.
Avoid polluting global scope.
console.log('Use scoped names and avoid globals')
      

25.1 Importance of Accessibility
Make apps usable by all users.
<button aria-label="Close">X</button>
      
25.2 Semantic HTML
Use proper HTML elements.
<nav>
  <ul>
    <li>Home</li>
    <li>About</li>
  </ul>
</nav>
      
25.3 ARIA Roles and Attributes
Add ARIA roles for assistive tech.
<div role="alert">Error occurred!</div>
      
25.4 Keyboard Navigation
Make UI accessible via keyboard.
<button @keydown.enter="submit">Submit</button>
      
25.5 Focus Management
Manage focus after actions.
methods: {
  focusInput() {
    this.$refs.input.focus()
  }
}
      
25.6 Using Vue-A11y Libraries
Libraries like vue-a11y-dialog help.
npm install vue-a11y-dialog
      
25.7 Testing Accessibility
Use tools like axe-core.
npm install @axe-core/vue
      
25.8 Responsive Design and A11y
Ensure UI works on all devices.
@media (max-width: 600px) {
  /* Responsive styles */
}
      
25.9 Color Contrast
Use accessible color palettes.
color: #000000; background-color: #ffffff;
      
25.10 Documentation & Guidelines
Follow WCAG standards.
https://www.w3.org/WAI/standards-guidelines/wcag/
      

26.1 Introduction to i18n
Make apps support multiple languages.
npm install vue-i18n
      
26.2 Setting up vue-i18n
Configure i18n plugin in Vue.
import { createI18n } from 'vue-i18n'

const i18n = createI18n({ locale: 'en', messages })
app.use(i18n)
      
26.3 Defining Messages
Store translations in objects.
const messages = {
  en: { welcome: 'Welcome' },
  fr: { welcome: 'Bienvenue' }
}
      
26.4 Using $t for Translation
Translate text in templates.
<p>{{ $t('welcome') }}</p>
      
26.5 Changing Locale Dynamically
Switch languages on user action.
i18n.global.locale = 'fr'
      
26.6 Pluralization
Handle singular/plural messages.
messages: {
  en: { car: 'car | cars' }
}
      
26.7 Date & Number Formatting
Localize dates and numbers.
i18n.global.dtf('en').format(new Date())
      
26.8 Lazy Loading Language Packs
Load only needed languages.
import('locales/fr.json').then(...)
      
26.9 Custom Directives for i18n
Create directives for translations.
app.directive('t', { mounted(el, binding) {
  el.textContent = i18n.global.t(binding.value)
}})
      
26.10 Testing i18n
Mock translations in tests.
jest.mock('vue-i18n', () => ({ t: key => key }))
      

27.1 Basics of Transitions
Use built-in <transition> component.
<transition name="fade">
  <div v-if="show">Hello</div>
</transition>
      
27.2 CSS Transition Classes
Customize enter and leave animations.
.fade-enter-active { transition: opacity 0.5s; }
.fade-leave-active { transition: opacity 0.5s; }
      
27.3 JavaScript Hooks
Control animations with JS hooks.
<transition
  @before-enter="beforeEnter"
  @enter="enter"
  @leave="leave"
>
      
27.4 List Transitions
Animate items in v-for lists.
<transition-group name="list">
  <div v-for="item in items" :key="item.id">{{ item.text }}</div>
</transition-group>
      
27.5 Using Third-Party Libraries
Integrate with Animate.css or GSAP.
import gsap from 'gsap'

gsap.to('.box', { x: 100, duration: 1 })
      
27.6 Transition Modes
Control timing with modes.
<transition mode="out-in"> ... </transition>
      
27.7 Custom Animation Classes
Add your own CSS animations.
@keyframes bounce {
  0%, 100% { transform: translateY(0) }
  50% { transform: translateY(-30px) }
}
      
27.8 Handling Animation Interruptions
Manage rapid state changes.
@keyframes fadeOut { ... }
      
27.9 Accessibility & Animations
Respect prefers-reduced-motion settings.
@media (prefers-reduced-motion: reduce) {
  * { transition: none !important; }
}
      
27.10 Debugging Animations
Use browser devtools.
Inspect animation keyframes.
document.querySelector('.box').style.animationPlayState = 'paused'
      

28.1 Introduction to SSR
Render Vue apps on the server.
npm install vue-server-renderer
      
28.2 Setting up SSR
Configure server with express and renderer.
// server.js
const express = require('express')
const { createRenderer } = require('vue-server-renderer')
const Vue = require('vue')

const server = express()
const renderer = createRenderer()

server.get('*', (req, res) => {
  const app = new Vue({
    data: { url: req.url },
    template: `<div>Hello SSR! URL is: {{ url }}</div>`
  })

  renderer.renderToString(app, (err, html) => {
    if (err) {
      res.status(500).end('Server Error')
      return
    }
    res.end(`
      <!DOCTYPE html>
      <html lang="en">
      <head><title>Vue SSR</title></head>
      <body>${html}</body>
      </html>
    `)
  })
})

server.listen(8080)
console.log('Server running at http://localhost:8080')
      
28.3 Creating App Entry for SSR
Export factory function for app.
// app.js
const { createSSRApp } = require('vue')

module.exports = function createApp() {
  const app = createSSRApp({
    data() {
      return { message: 'Hello from SSR app!' }
    },
    template: '<div>{{ message }}</div>'
  })
  return app
}
      
28.4 Hydration
Client reuses server markup.
// main.js (client entry)
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// Hydrate: attach Vue to existing server-rendered markup
app.mount('#app')  // Vue 3 hydrates automatically if markup exists
      
28.5 Data Prefetching
Fetch data on server before render.
export default {
  async asyncData() {
    // Pretend fetching data from API
    const data = await fetch('https://api.example.com/data').then(res => res.json())
    return { items: data }
  },
  data() {
    return { items: [] }
  },
  template: '<ul><li v-for="item in items" :key="item.id">{{ item.name }}</li></ul>'
}
      
28.6 Cache Strategies
Cache server renders for speed.
// server.js cache example
const LRU = require('lru-cache')
const cache = new LRU({ max: 100, maxAge: 1000 * 60 * 15 }) // 15 minutes cache

server.get('*', (req, res) => {
  const cachedPage = cache.get(req.url)
  if (cachedPage) {
    return res.end(cachedPage)
  }

  // render app ...
  renderer.renderToString(app, (err, html) => {
    if (!err) {
      cache.set(req.url, html)
    }
    res.end(html)
  })
})
      
28.7 Handling Routing with SSR
Match routes on server.
// router.js (example)
import { createRouter, createMemoryHistory } from 'vue-router'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

export function createSSRRouter() {
  return createRouter({
    history: createMemoryHistory(),
    routes,
  })
}

// server.js
const router = createSSRRouter()
router.push(req.url)
router.isReady().then(() => {
  const app = createApp()
  app.use(router)
  // render...
})
      
28.8 Dealing with State Transfer
Send state from server to client.
// In server render:
const state = { user: 'John Doe', loggedIn: true }
renderer.renderToString(app, (err, html) => {
  res.end(`
    <div id="app">${html}</div>
    <script>
      window.__INITIAL_STATE__ = ${JSON.stringify(state)}
    </script>
  `)
})

// In client entry:
const state = window.__INITIAL_STATE__
const app = createApp()
app.provide('initialState', state)
app.mount('#app')
      
28.9 Error Handling in SSR
Return error pages.
renderer.renderToString(app, (err, html) => {
  if (err) {
    if (err.code === 404) {
      res.status(404).end('Page Not Found')
    } else {
      res.status(500).end('Internal Server Error')
    }
  } else {
    res.end(html)
  }
})
      
28.10 Deploying SSR Apps
Use Node.js servers or platforms.
# Use pm2 to start server in production
pm2 start server.js --name vue-ssr-app

# Check logs
pm2 logs vue-ssr-app
      

29.1 Understanding Security Risks
Prevent XSS, CSRF, injection attacks.
function sanitize(input) {
  const div = document.createElement('div')
  div.textContent = input
  return div.innerHTML
}
// Usage:
const userInput = '<script>alert("XSS")</script>'
const safeInput = sanitize(userInput)
console.log(safeInput) // &lt;script&gt;alert("XSS")&lt;/script&gt;
      
29.2 Content Security Policy (CSP)
Restrict sources for scripts/styles.
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'">
      
29.3 Sanitizing Inputs
Use libraries like DOMPurify.
import DOMPurify from 'dompurify'

const dirty = '<img src=x onerror=alert(1)>'
const clean = DOMPurify.sanitize(dirty)
console.log(clean) // <img src="x">
      
29.4 Avoiding Inline JavaScript
Use external scripts.
<!-- Good: External JS file -->
<script src="app.js"></script>

<!-- Bad: Inline script -->
<script>alert('Hello')</script>
      
29.5 Safe Event Handling
Avoid eval and dangerous APIs.
<button @click="handleClick">Click Me</button>

methods: {
  handleClick() {
    alert('Button clicked safely')
  }
}
      
29.6 Authentication & Authorization
Secure routes and APIs.
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isUserLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})
      
29.7 Securing Vuex State
Avoid storing sensitive data.
const store = createStore({
  state: {
    token: null // don't store sensitive info permanently here
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    }
  }
})
      
29.8 HTTPS & Secure Headers
Use HTTPS and security headers.
// Express example with helmet middleware
const helmet = require('helmet')
app.use(helmet()) // sets secure headers automatically
      
29.9 Dependency Audits
Regularly check for vulnerabilities.
npm audit
npm audit fix
      
29.10 Keeping Up-to-Date
Update Vue and dependencies often.
npm update vue
npm outdated
      

30.1 Lazy Loading Components
Load components only when needed.
const AsyncComp = () => import('./AsyncComp.vue')

// Usage in template:
// <AsyncComp />
      
30.2 Debouncing Input
Reduce rapid event firing.
function debounce(fn, delay) {
  let timeout
  return (...args) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => fn(...args), delay)
  }
}

// Usage
const debouncedSearch = debounce(() => {
  console.log('Search triggered')
}, 300)
      
30.3 Virtual Scrolling
Efficiently render large lists.
<template>
  <virtual-scroller :items="items"></virtual-scroller>
</template>

<script>
import VirtualScroller from 'vue-virtual-scroller'
export default {
  components: { VirtualScroller },
  data() {
    return { items: Array(1000).fill().map((_, i) => 'Item ' + i) }
  }
}
</script>
      
30.4 Memoization
Cache expensive calculations.
import { computed } from 'vue'

const expensiveFn = (data) => {
  // some heavy calculation
  return data.reduce((a, b) => a + b, 0)
}

const data = [1, 2, 3, 4, 5]

const result = computed(() => expensiveFn(data))

console.log(result.value) // 15
      
30.5 Using Web Workers
Run heavy tasks off main thread.
// worker.js
self.onmessage = function(e) {
  const result = e.data * 2
  self.postMessage(result)
}

// main.js
const worker = new Worker('worker.js')
worker.onmessage = (e) => console.log('Result from worker:', e.data)
worker.postMessage(10)
      
30.6 Optimizing Reactivity
Use shallowReactive where suitable.
import { shallowReactive } from 'vue'

const state = shallowReactive({
  user: { name: 'Alice', age: 30 }
})

// Changes to nested objects won't trigger reactivity
state.user.name = 'Bob' // won't trigger updates
      
30.7 Reducing Watchers
Avoid unnecessary watchers.
import { watchEffect } from 'vue'

watchEffect(() => {
  console.log('Reactive effect runs')
  // Avoid watching too many variables unnecessarily
})
      
30.8 Server-Side Caching
Cache SSR output.
const cache = new Map()

function renderPage(url) {
  if (cache.has(url)) {
    return cache.get(url)
  }
  const html = renderApp(url)
  cache.set(url, html)
  return html
}
      
30.9 Tree Shaking
Remove unused code during build.
# In package.json scripts
"build": "vue-cli-service build --modern --target app --report --tree-shake"
      
30.10 Profiling Performance
Use browser and Vue Devtools profiling.
performance.mark('start')

// ... some Vue rendering or code ...

performance.mark('end')
performance.measure('myMeasurement', 'start', 'end')

const measures = performance.getEntriesByName('myMeasurement')
console.log(measures)