1. Vue.js 简介与环境搭建
1.1 什么是 Vue.js?
Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。它采用自底向上增量开发的设计,核心库只关注视图层,易于上手,也便于与第三方库或既有项目整合。Vue 的核心特性包括:
响应式数据绑定
:自动更新 DOM
组件化开发
:可复用的 UI 构建块
虚拟 DOM
:高效的 DOM 更新机制
1.2 环境搭建
方式一:CDN 引入(适合初学者)
{{ message }}
当前计数: {{ count }}
方式二:使用 Vite 创建项目(推荐)
# 安装 Node.js (v16+)
# 创建项目
npm create vue@latest
# 进入项目目录
cd my-vue-project
# 安装依赖
npm install
# 启动开发服务器
npm run dev
方式三:使用 Vue CLI(传统方式)
# 全局安装 Vue CLI
npm install -g @vue/cli
# 创建项目
vue create my-vue-project
# 选择配置(初学者建议选择 Default 或 Manual 选择 Vue 3)
# 启动项目
cd my-vue-project
npm run serve
2. Vue 核心概念详解
2.1 响应式数据系统
Vue 3 使用 Proxy 实现响应式系统,这是 Vue 3 相比 Vue 2 的重大改进。
// Vue 3 响应式示例
const { reactive, ref, computed, watch } = Vue;
const app = Vue.createApp({
setup() {
// ref 用于基本类型
const count = ref(0);
// reactive 用于对象
const state = reactive({
user: {
name: ‘张三’,
age: 25
},
todos: [
{ id: 1, text: ‘学习 Vue’, done: true },
{ id: 2, text: ‘完成项目’, done: false }
]
});
// 计算属性
const doubleCount = computed(() => count.value * 2);
const adultUsers = computed(() => {
return state.todos.filter(todo => !todo.done);
});
// 侦听器
watch(count, (newVal, oldVal) => {
console.log(`计数从 ${oldVal} 变为 ${newVal}`);
});
// 方法
const increment = () => {
count.value++;
};
const addUser = () => {
state.user.age++;
};
return {
count,
state,
doubleCount,
adultUsers,
increment,
addUser
};
}
});
app.mount(‘#app’);
2.2 模板语法与指令
插值与表达式
{{ message }}
{{ count * 2 }}
{{ message.split(”).reverse().join(”) }}
这是一个条件显示的段落
你输入了: {{ inputValue }}
常用指令详解
const app = Vue.createApp({
data() {
return {
message: ‘Hello Vue!’,
showParagraph: true,
url: ‘https://vuejs.org’,
tooltip: ‘Vue 官网’,
inputValue: ”,
items: [‘苹果’, ‘香蕉’, ‘橙子’],
users: [
{ id: 1, name: ‘Alice’, age: 25 },
{ id: 2, name: ‘Bob’, age: 30 },
{ id: 3, name: ‘Charlie’, age: 35 }
],
selectedUser: null,
activeClass: ‘active’,
errorClass: ‘error’,
dynamicStyles: {
color: ‘red’,
fontSize: ’20px’
}
}
},
methods: {
handleClick() {
this.message = ‘你点击了按钮!’;
this.showParagraph = !this.showParagraph;
},
selectUser(user) {
this.selectedUser = user;
}
}
});
app.mount(‘#app’);
- {{ index + 1 }}. {{ item }}
| {{ user.name }} | {{ user.age }} |
2.3 组件系统
组件是 Vue 的核心概念,允许我们将 UI 拆分为独立可复用的部分。
全局组件
// 定义全局组件
Vue.component(‘my-button’, {
props: [‘label’, ‘type’],
template: `
`,
methods: {
handleClick() {
this.$emit(‘click’);
}
}
});
// 使用组件
const app = Vue.createApp({
template: `
`,
methods: {
handlePrimary() {
alert(‘主要按钮被点击’);
},
handleDanger() {
alert(‘危险按钮被点击’);
}
}
});
局部组件(推荐)
// 子组件:UserCard.vue
const UserCard = {
props: {
user: {
type: Object,
required: true
},
compact: {
type: Boolean,
default: false
}
},
template: `
{{ user.name }}
年龄: {{ user.age }} | 邮箱: {{ user.email }}
`
};
// 父组件
const app = Vue.createApp({
components: {
‘user-card’: UserCard
},
data() {
return {
users: [
{ id: 1, name: ‘Alice’, age: 25, email: ‘alice@example.com’ },
{ id: 2, name: ‘Bob’, age: 30, email: ‘bob@example.com’ }
]
}
},
template: `
用户列表
`
});
3. Vue 3 组合式 API(Composition API)
3.1 setup() 函数
setup() 是 Vue 3 中引入的新特性,是组合式 API 的入口点。
const {
ref,
reactive,
computed,
watch,
onMounted,
onUpdated,
onUnmounted
} = Vue;
const CounterComponent = {
setup() {
// 响应式状态
const count = ref(0);
const state = reactive({
message: ‘Hello’,
nested: {
value: 42
}
});
// 计算属性
const doubleCount = computed(() => count.value * 2);
// 方法
const increment = () => {
count.value++;
state.nested.value++;
};
// 侦听器
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});
// 生命周期钩子
onMounted(() => {
console.log(‘组件已挂载’);
// 可以在这里进行 API 调用
});
onUpdated(() => {
console.log(‘组件已更新’);
});
onUnmounted(() => {
console.log(‘组件已卸载’);
// 清理工作
});
// 返回模板中使用的数据和方法
return {
count,
state,
doubleCount,
increment
};
},
template: `
计数: {{ count }}
双倍: {{ doubleCount }}
消息: {{ state.message }}
嵌套值: {{ state.nested.value }}
`
};
3.2 自定义组合式函数
组合式函数是 Vue 3 的强大特性,允许你封装和重用有状态逻辑。
// composables/useCounter.js
function useCounter(initialValue = 0) {
const count = ref(initialValue);
const increment = () => count.value++;
const decrement = () => count.value–;
const reset = () => count.value = initialValue;
// 侦听计数变化并存储到 localStorage
watch(count, (newVal) => {
localStorage.setItem(‘counter’, newVal);
});
// 从 localStorage 恢复
const saved = localStorage.getItem(‘counter’);
if (saved) {
count.value = parseInt(saved);
}
return {
count,
increment,
decrement,
reset
};
}
// composables/useUser.js
function useUser() {
const user = ref(null);
const loading = ref(false);
const error = ref(null);
const fetchUser = async (id) => {
loading.value = true;
error.value = null;
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) throw new Error(‘获取用户失败’);
user.value = await response.json();
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
};
return {
user,
loading,
error,
fetchUser
};
}
// 在组件中使用
const MyComponent = {
setup() {
// 使用自定义组合式函数
const { count, increment, decrement, reset } = useCounter(10);
const { user, loading, error, fetchUser } = useUser();
// 组合多个组合式函数
const loadUser = () => {
fetchUser(count.value);
};
return {
count,
increment,
decrement,
reset,
user,
loading,
error,
loadUser
};
},
template: `
计数器
当前值: {{ count }}
用户信息
姓名: {{ user.name }}
邮箱: {{ user.email }}
`
};
4. 实战项目:待办事项应用(Todo List)
4.1 项目结构
todo-app/
├── index.html
├── app.js
├── style.css
└── components/
├── TodoInput.vue
├── TodoList.vue
├── TodoItem.vue
└── TodoFilter.vue
4.2 完整实现代码
index.html
📋 我的待办事项
使用 Vue.js 构建的任务管理器
style.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.subtitle {
opacity: 0.9;
font-size: 1.1em;
}
.todo-app {
padding: 30px;
}
.input-section {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.input-section input {
flex: 1;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 16px;
transition: border-color 0.3s;
}
.input-section input:focus {
outline: none;
border-color: #667eea;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
}
.btn-secondary {
background: #f0f0f0;
color: #333;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.btn-danger {
background: #ff4757;
color: white;
}
.btn-danger:hover {
background: #e04050;
}
.btn-small {
padding: 6px 12px;
font-size: 14px;
}
.filter-section {
display: flex;
gap: 10px;
margin-bottom: 20px;
justify-content: center;
}
.filter-btn {
padding: 8px 16px;
border: 2px solid #e0e0e0;
background: white;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s;
}
.filter-btn.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.todo-list {
list-style: none;
}
.todo-item {
display: flex;
align-items: center;
padding: 16px;
border-bottom: 1px solid #f0f0f0;
transition: background 0.2s;
gap: 12px;
}
.todo-item:hover {
background: #f8f9fa;
}
.todo-item.completed {
opacity: 0.6;
text-decoration: line-through;
}
.todo-item input[type=”checkbox”] {
width: 20px;
height: 20px;
cursor: pointer;
}
.todo-text {
flex: 1;
font-size: 16px;
color: #333;
}
.todo-actions {
display: flex;
gap: 8px;
}
.stats {
display: flex;
justify-content: space-around;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-top: 20px;
}
.stat-item {
text-align: center;
}
.stat-value {
font-size: 24px;
font-weight: bold;
color: #667eea;
}
.stat-label {
font-size: 14px;
color: #666;
}
.empty-state {
text-align: center;
padding: 40px;
color: #999;
}
.empty-state-icon {
font-size: 48px;
margin-bottom: 10px;
}
/* 动画 */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s, transform 0.3s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
transform: translateX(-20px);
}
.list-move {
transition: transform 0.3s;
}
app.js
// TodoInput.vue – 输入组件
const TodoInput = {
props: {
modelValue: {
type: String,
default: ”
}
},
emits: [‘update:modelValue’, ‘add’],
template: `
`
};
// TodoItem.vue – 单个待办项
const TodoItem = {
props: {
todo: {
type: Object,
required: true
}
},
emits: [‘toggle’, ‘delete’, ‘edit’],
template: `
{{ todo.text }}
`
};
// TodoFilter.vue – 过滤器
const TodoFilter = {
props: {
filter: {
type: String,
default: ‘all’
}
},
emits: [‘update:filter’],
template: `
`
};
// TodoList.vue – 主应用组件
const TodoList = {
components: {
TodoInput,
TodoItem,
TodoFilter
},
setup() {
const { ref, computed, onMounted, watch } = Vue;
// 响应式状态
const todos = ref([]);
const newTodo = ref(”);
const filter = ref(‘all’);
const editingTodo = ref(null);
// 从 localStorage 加载数据
const loadTodos = () => {
const saved = localStorage.getItem(‘vue-todos’);
if (saved) {
try {
todos.value = JSON.parse(saved);
} catch (e) {
console.error(‘加载数据失败:’, e);
}
}
};
// 保存到 localStorage
const saveTodos = () => {
localStorage.setItem(‘vue-todos’, JSON.stringify(todos.value));
};
// 计算属性
const filteredTodos = computed(() => {
switch (filter.value) {
case ‘active’:
return todos.value.filter(t => !t.completed);
case ‘completed’:
return todos.value.filter(t => t.completed);
default:
return todos.value;
}
});
const stats = computed(() => {
const total = todos.value.length;
const completed = todos.value.filter(t => t.completed).length;
const active = total – completed;
return { total, completed, active };
});
// 方法
const addTodo = () => {
if (!newTodo.value.trim()) return;
if (editingTodo.value) {
// 编辑模式
editingTodo.value.text = newTodo.value;
editingTodo.value = null;
} else {
// 添加模式
todos.value.push({
id: Date.now(),
text: newTodo.value,
completed: false,
createdAt: new Date().toISOString()
});
}
newTodo.value = ”;
};
const toggleTodo = (id) => {
const todo = todos.value.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
}
};
const deleteTodo = (id) => {
if (confirm(‘确定要删除这个待办事项吗?’)) {
todos.value = todos.value.filter(t => t.id !== id);
if (editingTodo.value?.id === id) {
editingTodo.value = null;
newTodo.value = ”;
}
}
};
const editTodo = (todo) => {
editingTodo.value = todo;
newTodo.value = todo.text;
};
const clearCompleted = () => {
if (confirm(‘确定要清除所有已完成的事项吗?’)) {
todos.value = todos.value.filter(t => !t.completed);
}
};
const clearAll = () => {
if (confirm(‘确定要清除所有事项吗?此操作不可恢复!’)) {
todos.value = [];
newTodo.value = ”;
editingTodo.value = null;
}
};
// 生命周期和侦听器
onMounted(() => {
loadTodos();
console.log(‘待办事项应用已加载’);
});
watch(todos, saveTodos, { deep: true });
return {
todos,
newTodo,
filter,
editingTodo,
filteredTodos,
stats,
addTodo,
toggleTodo,
deleteTodo,
editTodo,
clearCompleted,
clearAll
};
},
template: `
暂无事项