Why Must data Be a Function in Vue Components?
In Vue components, the data option must be a function that returns an object. This ensures each component instance gets its own isolated data object. If data were a plain object, all instances would share the same reference, leading to unintended side effects where changes in one instance affect others.
Types of Vue Slots
Slots enable content distribution from parent to child components, enhancing reusability and flexibility:
- Default Slot: The unnamed slot that renders the first child node passed by the parent.
- Named Slot: Uses the
nameattribute to target specific slots when multiple insertion points exist. - Scoped Slot: Allows the child component to pass data to the parent, which then decides how to render it using slot props.
Purpose of the key Attribute in v-for
The key attribute provides a unique identifier for each node in a list, helping Vue’s virtual DOM diffing algorithm track element identity. This improves rendering accuracy and performance—especially when dynamically adding, removing, or reordering items. Omitting key can cause unexpected behavior in stateful components (e.g., form inputs retaining incorrect values).
Vue Component Communication Patterns
-
Parent to Child (Props)
<!-- Parent --> <ChildComponent :message="greeting" /> <!-- Child --> export default { props: ['message'] } -
Child to Parent (Custom Events)
<!-- Parent --> <ChildComponent @notify="handleNotification" /> <!-- Child --> this.$emit('notify', payload); -
Global Event Bus
// bus.js import Vue from 'vue'; export const EventBus = new Vue(); // Emitter EventBus.$emit('event-name', data); // Listener EventBus.$on('event-name', callback); -
Vuex State Management Centralized store with
state,mutations,actions, andgetters. Modules allow feature-based organization.// Accessing state computed: { ...mapGetters(['sidebar']) } -
Route-Based Communication Pass data between routes via
paramsorquery:this.$router.push({ name: 'Profile', params: { id: 123 } }); -
Client-Side Storage Use
localStorage,sessionStorage, or cookies for persistent or session-scoped data:import Cookies from 'js-cookie'; Cookies.set('token', value, { expires: 30 });
Vue Lifecycle Hooks
beforeCreate: Instance initialized; reactive data and events not yet set up.created: Data observation, computed properties, methods, and watchers are ready. Ideal for API calls.beforeMount: Template compilation begins;$elnot yet available.mounted: Component attached to DOM; safe to access or manipulate DOM elements.beforeUpdate: Called when reactive data changes, before DOM patching.updated: DOM updated; avoid changing state here to prevent infinite loops.beforeDestroy: Cleanup stage (e.g., cancel timers, unsubscribe listeners).destroyed: All bindings and child components removed.activated/deactivated: Exclusive to<keep-alive>; triggered when component is toggled in/out of cache.