Core Concepts and Implementation Patterns in Vue.js 2
Vue Build Tools
Project Initialization
Set up a Vue environment using the CLI tool. Node.js is required. Upgrade to compatible versions.
# Check CLI version (requires 4.5.0+ for Vue 3 compatibility context)
vue --version
# Global installation
npm install @vue/cli@5.0.0 -g
Project scaffolding command:
vue create frontend-demo
Handling Sass dependencies if compilation fails:
npm install sass-loader@7.3.1 node-sass@4.14.1
Application Entry Point
Refer to official documentation. Instantiate the application root.
import Vue from 'vue';
import Router from '@/router';
import Store from '@/store';
import App from '@/App.vue';
const app = new Vue({
router: Router,
store: Store,
render(h) { return h(App); },
}).$mount('#root');
Note: Template property allows string-based HTML templates, whereas Render functions offer higher performance. Mounting occurs via el or $mount.
Compilation Strategies
Two main distributions exist:
runtime-compiler: Compiles templatess in the browser (AST -> Render -> VDOM). Slower bundle size.runtime-only: Skips template compilation (Render -> VDOM). Faster, smaller bundles.
Component Lifecycle
The execution order follows a strict sequence. Parent hooks fire before children during creation, and vice versa during destruction.
export default {
beforeCreate() { console.log('init start'); },
created() { /* Data observer initialized */ },
beforeMount() { console.log('template compiled'); },
mounted() { console.log('DOM available'); },
activated() {}, // Keep-alive activation
deactivated() {}, // Keep-alive deactivation
beforeUpdate() { /* Data changed, view updating */ },
updated() { /* DOM reflects data changes */ },
beforeDestroy() { console.log('cleanup preparing'); },
destroyed() { console.log('instance removed'); }
};
Directives & Events
Visibility control uses CSS toggling (v-show) or DOM manipulation (v-if). Prioritize v-if over v-for in Vue 2 due to precedence rules.
<div :class="isActive ? 'active' : ''">{{ label }}</div>
<input v-model.trim.lazy="searchQuery">
Event Binding modifiers:
.stop: Prevent bubbling..prevent: Stop form submission defaults..capture: Handle event propagation order..once: Trigger a single time.
Argument handling differs based on call signature:
// Handler receives event object automatically
handleClick () { console.log(event.target); }
// Handler requires explicit arguments
handleClickWithArg(e, customData) { console.log(customData); }
Global Interfaces
Filters allow transformation of display values. Register globally or locally. Custom directives manipulate DOM nodes directly upon binding. Components register using kebab-case for HTML usage.
Configuration Options
State Management: data must return a fresh object per instance to avoid reference sharing issues.
Props: Enforce types and defaults. Default values for objects/arrays require factory functions.
Computed: Caches results unless dependencies chenge. Read-only by default unless getter/setter defined.
Watchers: Monitor reactive changes. Enable immediate execution or deep observation for complex objects.
Mixins: Reusable logic. Merging strategy prioritizes component options over mixin definitions for conflicts.
Instance Properties
Access internal references via $refs. Emit custom events upwards using $emit. Use $nextTick to execute logic after DOM updates cycle finishes. $forceUpdate forces re-rendering manually. $attrs captures non-prop attributes passed from parents.
Routing System
Install vue-router@3. Configure paths, redirects, and lazy-loaded components. Dynamic segments (e.g., /user/:id) populate route params. Query parameters append to URLs, while params stay embedded. Navigation guards control access and transitions.
const routes = [
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
},
{ path: '*', redirect: '/' }
];
const router = new VueRouter({
mode: 'history',
base: '/',
scrollBehavior: () => ({ x: 0, y: 0 }),
routes
});
Guard execution flows through global checks before resolving async components. Handle navigation failures gracefully to prevent error logs on duplicate clicks.
State Management Library
Centralized store (Vuex) maintains reactive state.
- State: Single source of truth.
- Mutations: Synchronous state mutations triggered by commits.
- Actions: Asynchronous operations committing mutations.
- Getters: Memoized derived state.
Modular architecture supports namespace isolation to prevent naming collisions. Helper functions (mapState, mapMutations) facilitate cleaner composition in component files.
Optimization & Troubleshooting
Reactivity: Vue 2 relies on Object.defineProperty. Adding/deleting properties requires Vue-specific methods ($set / $delete) to trigger updates. Arrays require mutation methods to notify observers.
Virtual DOM: Changes compared via diff algorithm using unique keys. Do not rely on array indices as keys to prevent rendering inefficiencies.
Scoped Styles: Apply component-local styles using <style scoped>. Access sibling styles cautiously.
Legacy Support: Polyfills may be necessary for older browsers like Internet Explorer. Conifgure Babel accordingly in webpack config.
Component hierarchy access exists via $parent, $children, $root, though prop drilling is preferred for maintainability.