Table of Contents
| Section | Time Estimate | What You’ll Learn |
|---|---|---|
| Introduction & Setup | 10 minutes | What is Vue? Install Vue (CDN, CLI, Vite) |
| Core Concepts | 15 minutes | Reactive data, templates, directives, components |
| State Management with Pinia | 5 minutes | Simplified state management |
| Routing with Vue Router | 5 minutes | Navigation between pages |
| Advanced Tips | 5 minutes | Computed properties, watchers, lifecycle hooks |
| Project Structure | 5 minutes | Organizing your Vue app |
| Practice Project: Todo App | 10 minutes | Build a functional todo list |
| Conclusion & Next Steps | 5 minutes | Recap and resources |
1. Introduction & Setup (10 minutes)
What is Vue.js?
Vue is a progressive framework—meaning you can start small (e.g., enhancing a static HTML page) and scale up to a full-featured single-page application (SPA). Key features:
- Reactive Data Binding: Automatically updates the DOM when data changes.
- Component-Based Architecture: Build reusable UI elements.
- Template Syntax: Familiar HTML-based templates with Vue-specific directives.
- Flexible: Integrates with other libraries (e.g., React, Angular) or stands alone.
Installing Vue: 3 Options
Option 1: CDN (Quick Start for Beginners)
For experimenting, add Vue directly to an HTML file via CDN:
<!-- Include Vue from CDN -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app">
{{ message }} <!-- Reactive interpolation -->
</div>
<script>
// Create a Vue app instance
const { createApp } = Vue;
createApp({
data() {
return {
message: "Hello, Vue!"
}
}
}).mount('#app'); // Mount to the DOM element with id "app"
</script>
Save this as index.html and open it in a browser. You’ll see “Hello, Vue!”—your first Vue app!
Option 2: Vue CLI (Structured Projects)
For larger apps, use Vue CLI (requires Node.js ≥14.18):
# Install Vue CLI globally
npm install -g @vue/cli
# Create a new project
vue create my-vue-app
# Follow prompts (choose Vue 3, default preset for simplicity)
cd my-vue-app
npm run serve # Start development server (usually at http://localhost:8080)
Option 3: Vite (Recommended for Modern Apps)
Vite is Vue’s official build tool (faster than CLI). Install it with:
# Create a Vite project
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install # Install dependencies
npm run dev # Start dev server (http://localhost:5173)
Pro Tip: Use Vite for new projects—it’s faster and has better HMR (Hot Module Replacement) than Vue CLI.
2. Core Concepts (15 minutes)
Reactive Data & the Vue Instance
At the heart of Vue is reactivity: when data changes, the UI updates automatically.
data()function: Returns an object of reactive properties.- Mounting: The
mount()method attaches the Vue app to a DOM element (e.g.,#app).
Example:
const app = createApp({
data() {
return {
count: 0, // Reactive property
todos: ["Learn Vue", "Build app"]
};
},
methods: { // Functions to modify data
increment() {
this.count++; // "this" refers to the app instance
}
}
});
app.mount("#app"); // Now, #app has access to count, todos, and increment
Templates & Directives
Vue templates use HTML with special “directives” (prefixed with v-) to add interactivity.
| Directive | Purpose | Example |
|---|---|---|
{{ }} | Text interpolation (reactive) | <p>{{ message }}</p> |
v-bind:attr | Bind HTML attributes reactively | <img v-bind:src="imageUrl"> (shorthand: :src) |
v-on: event | Listen to DOM events | <button v-on:click="increment"> (shorthand: @click) |
v-if/v-else | Conditional rendering | <p v-if="isLoggedIn">Welcome!</p> |
v-for | Loop over arrays/objects | <li v-for="todo in todos">{{ todo }}</li> |
v-model | Two-way data binding (form inputs) | <input v-model="username"> |
Components: Reusable UI Blocks
Components are self-contained Vue instances—think “widgets” (buttons, cards, navigation bars).
Step 1: Define a component
// Define a "TodoItem" component
const TodoItem = {
props: ['todo'], // Accept data from parent via props
template: `<li>{{ todo }}</li>`
};
Step 2: Use it in the app
const app = createApp({
data() {
return { todos: ["Learn components", "Build app"] };
},
components: { TodoItem } // Register the component
});
app.mount("#app");
Step 3: Template usage
<div id="app">
<todo-item v-for="todo in todos" :todo="todo"></todo-item>
</div>
3. State Management with Pinia (5 minutes)
For apps with shared state (e.g., user authentication, cart items), use Pinia (Vue’s official state manager, replacing Vuex).
Install Pinia
npm install pinia
Create a Store
// stores/todoStore.js
import { defineStore } from 'pinia';
export const useTodoStore = defineStore('todos', {
state: () => ({ items: [] }), // Reactive state
actions: { // Modify state
addTodo(todo) {
this.items.push(todo);
},
deleteTodo(index) {
this.items.splice(index, 1);
}
}
});
Use the Store in a Component
import { useTodoStore } from './stores/todoStore';
export default {
setup() {
const todoStore = useTodoStore();
return { todoStore }; // Expose to template
}
};
<!-- Template -->
<div>
<input v-model="newTodo" @keyup.enter="todoStore.addTodo(newTodo)">
<ul>
<li v-for="(todo, index) in todoStore.items" @click="todoStore.deleteTodo(index)">
{{ todo }}
</li>
</ul>
</div>
4. Routing with Vue Router (5 minutes)
Vue Router handles navigation between “pages” in SPAs.
Install Vue Router
npm install vue-router@4
Basic Setup
- Define routes in
router/index.js:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
- Register router in
main.js:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
- Use in template:
<!-- App.vue -->
<template>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view /> <!-- Renders the current route's component -->
</template>
5. Advanced Tips (5 minutes)
Computed Properties vs. Methods
- Methods: Run on every re-render. Use for actions (e.g.,
increment()). - Computed Properties: Cached, re-run only when dependencies change. Use for derived data:
computed: { reversedMessage() { return this.message.split('').reverse().join(''); } }
Watchers
Track changes to reactive data:
watch: {
username(newVal, oldVal) {
console.log(`Username changed from ${oldVal} to ${newVal}`);
}
}
Lifecycle Hooks
Vue instances go through stages (created, mounted, updated, destroyed). Use hooks to run code at specific stages:
created() {
// Runs when the instance is initialized (data is reactive)
this.loadData();
},
mounted() {
// Runs after the DOM is mounted
this.setupEventListeners();
}
6. Project Structure (5 minutes)
A typical Vue project (via Vite or Vue CLI) has this structure:
my-vue-app/
├── node_modules/ # Dependencies
├── public/ # Static files (index.html, favicon)
├── src/ # Source code
│ ├── assets/ # Images, CSS, fonts
│ ├── components/ # Reusable components (Button.vue, Card.vue)
│ ├── views/ # Page components (Home.vue, About.vue)
│ ├── router/ # Routing config (index.js)
│ ├── stores/ # Pinia stores (todoStore.js)
│ ├── App.vue # Root component
│ └── main.js # Entry point (mounts app)
├── package.json # Project config
└── vite.config.js # Vite settings (if using Vite)
7. Practice Project: Todo App (10 minutes)
Let’s build a todo app to tie together concepts!
Step 1: Set Up the Component
Create src/components/TodoApp.vue:
<template>
<div class="todo-app">
<h1>Todo List</h1>
<input
v-model="newTodo"
@keyup.enter="addTodo"
placeholder="Add a new todo..."
>
<ul>
<li
v-for="(todo, index) in todos"
:key="index"
@click="removeTodo(index)"
>
{{ todo }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newTodo: '',
todos: []
};
},
methods: {
addTodo() {
if (this.newTodo.trim()) {
this.todos.push(this.newTodo);
this.newTodo = ''; // Clear input
}
},
removeTodo(index) {
this.todos.splice(index, 1);
}
}
};
</script>
<style scoped>
/* Add basic styling */
.todo-app { max-width: 400px; margin: 2rem auto; padding: 1rem; }
li { cursor: pointer; margin: 0.5rem 0; }
li:hover { text-decoration: line-through; }
</style>
Step 2: Use the Component in App.vue
<template>
<TodoApp />
</template>
<script>
import TodoApp from './components/TodoApp.vue';
export default {
components: { TodoApp }
};
</script>
Step 3: Run the App
npm run dev
Visit http://localhost:5173—you’ll have a working todo app with add/remove functionality!
8. Conclusion & Next Steps (5 minutes)
Recap
In 60 minutes, you learned:
- Vue basics: reactivity, templates, directives, components.
- State management with Pinia.
- Routing with Vue Router.
- Project structure and a practice todo app.
Next Steps
- Deep Dive: Read the Vue.js Documentation.
- Composition API: Learn Vue 3’s Composition API (more scalable than Options API).
- Build More Apps: Try a weather app, blog, or e-commerce site.
- Deploy: Host your app on Vercel, Netlify, or GitHub Pages.
References
Happy coding with Vue! 🚀