Vue.js是一个用于构建用户界面的渐进式JavaScript框架。本章将介绍Vue.js的核心概念、特点以及在现代前端开发中的地位。
1.1 什么是Vue.js
Vue.js简介
Vue.js(读音 /vjuː/,类似于 view)是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue被设计为可以自底向上逐层应用。
// Vue.js的核心理念示例
const { createApp } = Vue
createApp({
data() {
return {
message: 'Hello Vue!'
}
}
}).mount('#app')
<!-- 对应的HTML模板 -->
<div id="app">
{{ message }}
</div>
Vue.js的特点
1. 渐进式框架
// 可以逐步引入Vue.js功能
// 1. 最简单的使用方式
const app = Vue.createApp({
data() {
return { count: 0 }
}
})
// 2. 添加组件
app.component('counter', {
data() {
return { count: 0 }
},
template: `
<button @click="count++">
点击了 {{ count }} 次
</button>
`
})
// 3. 添加路由(Vue Router)
// 4. 添加状态管理(Vuex/Pinia)
// 5. 构建工具(Vite/Vue CLI)
2. 响应式数据绑定
// Vue 3 Composition API
import { ref, reactive, computed } from 'vue'
export default {
setup() {
// 响应式引用
const count = ref(0)
// 响应式对象
const state = reactive({
name: 'Vue.js',
version: '3.x'
})
// 计算属性
const doubleCount = computed(() => count.value * 2)
// 方法
const increment = () => {
count.value++
}
return {
count,
state,
doubleCount,
increment
}
}
}
3. 组件化开发
<!-- UserCard.vue -->
<template>
<div class="user-card">
<img :src="user.avatar" :alt="user.name" />
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script>
export default {
name: 'UserCard',
props: {
user: {
type: Object,
required: true
}
},
emits: ['message-sent'],
methods: {
sendMessage() {
this.$emit('message-sent', this.user.id)
}
}
}
</script>
<style scoped>
.user-card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
margin: 8px;
}
.user-card img {
width: 64px;
height: 64px;
border-radius: 50%;
}
</style>
4. 虚拟DOM
// Vue的虚拟DOM概念
// 真实DOM操作(性能较低)
document.getElementById('app').innerHTML = '<h1>Hello World</h1>'
// Vue虚拟DOM(性能优化)
const vnode = {
tag: 'h1',
children: 'Hello World'
}
// Vue会智能地比较虚拟DOM差异,只更新必要的部分
const app = createApp({
data() {
return {
title: 'Hello World',
items: ['item1', 'item2', 'item3']
}
},
template: `
<div>
<h1>{{ title }}</h1>
<ul>
<li v-for="item in items" :key="item">
{{ item }}
</li>
</ul>
</div>
`
})
1.2 Vue.js的发展历程
版本演进
// Vue 1.x (2014-2016)
// 简单的数据绑定和组件系统
new Vue({
el: '#app',
data: {
message: 'Hello Vue 1.x'
}
})
// Vue 2.x (2016-2020)
// 虚拟DOM、服务端渲染、更好的性能
new Vue({
el: '#app',
data() {
return {
message: 'Hello Vue 2.x'
}
},
methods: {
greet() {
alert(this.message)
}
}
})
// Vue 3.x (2020至今)
// Composition API、更好的TypeScript支持、性能提升
import { createApp } from 'vue'
const app = createApp({
data() {
return {
message: 'Hello Vue 3.x'
}
}
})
app.mount('#app')
主要里程碑
2014年2月 - Vue.js 0.6 发布
2015年10月 - Vue.js 1.0 "Evangelion" 发布
2016年9月 - Vue.js 2.0 "Ghost in the Shell" 发布
2020年9月 - Vue.js 3.0 "One Piece" 发布
2022年2月 - Vue.js 3.2 成为新的默认版本
2023年12月 - Vue.js 3.4 "🏀 Slam Dunk" 发布
1.3 Vue.js生态系统
核心库
// 1. Vue Router - 路由管理
import { createRouter, createWebHistory } from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
// 2. Pinia - 状态管理
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
// 3. Vue DevTools - 开发工具
// 浏览器扩展,用于调试Vue应用
构建工具
# Vite - 现代构建工具
npm create vue@latest my-vue-app
cd my-vue-app
npm install
npm run dev
# Vue CLI - 传统构建工具
npm install -g @vue/cli
vue create my-project
cd my-project
npm run serve
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true
},
build: {
outDir: 'dist',
sourcemap: true
}
})
UI组件库
// Element Plus
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
// Ant Design Vue
import { createApp } from 'vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
import App from './App.vue'
const app = createApp(App)
app.use(Antd)
app.mount('#app')
// Vuetify
import { createApp } from 'vue'
import { createVuetify } from 'vuetify'
import 'vuetify/styles'
import App from './App.vue'
const vuetify = createVuetify()
const app = createApp(App)
app.use(vuetify)
app.mount('#app')
1.4 Vue.js vs 其他框架
Vue.js vs React
// Vue.js 组件
// UserProfile.vue
<template>
<div class="user-profile">
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
<button @click="updateProfile">更新资料</button>
</div>
</template>
<script>
export default {
props: ['user'],
methods: {
updateProfile() {
// 更新逻辑
}
}
}
</script>
// React 组件
import React from 'react'
function UserProfile({ user }) {
const updateProfile = () => {
// 更新逻辑
}
return (
<div className="user-profile">
<h2>{user.name}</h2>
<p>{user.email}</p>
<button onClick={updateProfile}>更新资料</button>
</div>
)
}
export default UserProfile
Vue.js vs Angular
// Vue.js 服务
// userService.js
export class UserService {
constructor() {
this.users = []
}
async getUsers() {
const response = await fetch('/api/users')
this.users = await response.json()
return this.users
}
}
// Angular 服务
// user.service.ts
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/api/users')
}
}
框架对比表
特性 | Vue.js | React | Angular |
---|---|---|---|
学习曲线 | 平缓 | 中等 | 陡峭 |
性能 | 优秀 | 优秀 | 良好 |
生态系统 | 丰富 | 非常丰富 | 完整 |
TypeScript支持 | 良好 | 优秀 | 原生支持 |
移动端支持 | NativeScript | React Native | Ionic |
企业采用 | 中等 | 高 | 高 |
1.5 Vue.js的应用场景
1. 单页应用(SPA)
// main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './views/Home.vue'
import About from './views/About.vue'
import Contact from './views/Contact.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp(App)
app.use(router)
app.mount('#app')
2. 渐进式增强
<!-- 现有的HTML页面 -->
<!DOCTYPE html>
<html>
<head>
<title>现有网站</title>
</head>
<body>
<div id="legacy-content">
<h1>现有内容</h1>
</div>
<!-- 添加Vue.js增强功能 -->
<div id="vue-widget">
<todo-list></todo-list>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
const { createApp } = Vue
createApp({
components: {
TodoList: {
data() {
return {
todos: ['学习Vue.js', '构建应用']
}
},
template: `
<ul>
<li v-for="todo in todos" :key="todo">
{{ todo }}
</li>
</ul>
`
}
}
}).mount('#vue-widget')
</script>
</body>
</html>
3. 服务端渲染(SSR)
// nuxt.config.js (Nuxt.js)
export default {
// 服务端渲染配置
ssr: true,
// 页面
pages: {
index: '~/pages/index.vue',
about: '~/pages/about.vue'
},
// 插件
plugins: [
'~/plugins/axios.js'
],
// 模块
modules: [
'@nuxtjs/axios',
'@nuxtjs/pwa'
]
}
4. 静态站点生成(SSG)
// VitePress配置
// .vitepress/config.js
export default {
title: 'Vue.js文档',
description: 'Vue.js学习指南',
themeConfig: {
nav: [
{ text: '指南', link: '/guide/' },
{ text: 'API', link: '/api/' },
{ text: '示例', link: '/examples/' }
],
sidebar: {
'/guide/': [
{
text: '基础',
items: [
{ text: '介绍', link: '/guide/introduction' },
{ text: '安装', link: '/guide/installation' }
]
}
]
}
}
}
5. 移动端应用
// Quasar Framework
// quasar.conf.js
module.exports = function (ctx) {
return {
// 支持的平台
supportTS: false,
supportIE: false,
// 构建目标
build: {
vueRouterMode: 'hash',
showProgress: true,
gzip: true,
analyze: true
},
// 开发服务器
devServer: {
https: false,
port: 8080,
open: true
},
// Cordova配置
cordova: {
id: 'org.cordova.quasar.app'
},
// Electron配置
electron: {
bundler: 'packager',
packager: {},
builder: {
appId: 'vue-electron-app'
}
}
}
}
1.6 学习路径规划
初学者路径
graph TD
A[HTML/CSS/JavaScript基础] --> B[Vue.js基础概念]
B --> C[模板语法和指令]
C --> D[组件基础]
D --> E[组件通信]
E --> F[路由管理]
F --> G[状态管理]
G --> H[项目实战]
学习计划
// 学习计划配置
const learningPlan = {
week1: {
topics: ['Vue.js基础概念', '环境搭建', '模板语法'],
practice: ['创建第一个Vue应用', '数据绑定练习'],
goals: '理解Vue.js核心概念和基本用法'
},
week2: {
topics: ['组件基础', '组件通信', '生命周期'],
practice: ['创建可复用组件', '父子组件通信'],
goals: '掌握组件化开发思想'
},
week3: {
topics: ['路由管理', '状态管理', 'HTTP请求'],
practice: ['多页面应用', '全局状态管理'],
goals: '构建完整的单页应用'
},
week4: {
topics: ['项目实战', '性能优化', '部署发布'],
practice: ['完整项目开发', '性能调优'],
goals: '独立开发和部署Vue.js应用'
}
}
实践项目建议
// 项目难度递进
const projects = [
{
level: 'beginner',
name: '待办事项应用',
features: ['添加任务', '删除任务', '标记完成'],
technologies: ['Vue 3', 'Composition API']
},
{
level: 'intermediate',
name: '博客系统',
features: ['文章列表', '文章详情', '分类筛选', '搜索功能'],
technologies: ['Vue 3', 'Vue Router', 'Axios']
},
{
level: 'advanced',
name: '电商平台',
features: ['商品展示', '购物车', '用户认证', '订单管理'],
technologies: ['Vue 3', 'Vue Router', 'Pinia', 'Element Plus']
}
]
本章小结
本章我们学习了:
- Vue.js基础概念:渐进式框架、响应式数据绑定、组件化开发
- Vue.js特点:虚拟DOM、双向数据绑定、指令系统
- 发展历程:从1.x到3.x的演进过程
- 生态系统:核心库、构建工具、UI组件库
- 框架对比:与React、Angular的异同
- 应用场景:SPA、SSR、SSG、移动端开发
- 学习路径:从基础到实战的完整规划
下一章预告
下一章我们将学习Vue.js的环境搭建,包括: - 开发环境配置 - 项目创建和管理 - 开发工具使用 - 调试技巧
练习题
基础练习
概念理解:
- 解释什么是渐进式框架
- 说明Vue.js的主要特点
- 比较Vue.js与其他框架的优缺点
代码阅读:
- 阅读Vue.js官方文档的快速开始部分
- 分析Vue.js的基本语法结构
- 理解响应式数据绑定的工作原理
进阶练习
环境准备:
- 安装Node.js和npm
- 了解Vue CLI和Vite的区别
- 准备代码编辑器和浏览器扩展
学习规划:
- 制定个人的Vue.js学习计划
- 选择适合的学习资源
- 确定实践项目目标
提示:Vue.js的学习重在实践,建议边学边做,通过项目来巩固理论知识。