目录
一、Vue 2.0 简介
1.1 什么是 Vue?
Vue 是一款轻量、渐进式的 JavaScript 框架,用于构建用户界面。它专注于视图层,易于上手,也支持复杂的单页应用开发。
1.2 Vue 2.x 的主要特性
- 响应式数据绑定
- 组件化开发
- 指令系统
- 生命周期钩子
- 计算属性 & 侦听器
- 内置过渡 & 动画支持
- 强大的插件生态
二、快速上手
2.1 引入 Vue
<!-- CDN 引入 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
2.2 创建第一个 Vue 实例
<div id="app">
<h1>{{ message }}</h1>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue 2!'
}
});
</script>
三、核心概念详解
3.1 模板语法
- 插值:{{ message }}
- 属性绑定::href=“url”
- 条件渲染:v-if / v-else / v-show
- 列表渲染:v-for
3.2 数据绑定
<div>{{ message }}</div>
<input v-model="message">
3.3 事件绑定
<button v-on:click="greet">点击</button>
<script>
methods: {
greet() {
alert('Hello Vue!');
}
}
</script>
3.4 计算属性 & 侦听器
<p>反转消息: {{ reversedMessage }}</p>
<script>
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
</script>
四、组件系统
4.1 定义全局组件
Vue.component('my-component', {
template: '<div>这是一个组件</div>'
});
4.2 单文件组件(*.vue 文件)
结构:
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: '单文件组件'
};
}
}
</script>
<style scoped>
div { color: blue; }
</style>
4.3 父子组件通信
- props 传值
<child :message="parentMsg"></child>
<script>
props: ['message']
</script>
- $emit 事件派发
<child @custom-event="parentMethod"></child>
<script>
// 子组件
this.$emit('custom-event', data);
</script>
五、指令系统
指令 | 作用 |
---|---|
v-bind | 动态绑定属性 |
v-model | 双向数据绑定 |
v-if | 条件渲染 |
v-show | 条件显示(不销毁 DOM) |
v-for | 列表循环 |
v-on | 绑定事件监听器 |
v-html | 输出 HTML 内容 |
v-cloak | 防止闪烁 |
六、生命周期钩子
钩子名 | 触发时机 |
---|---|
beforeCreate | 实例初始化后,数据观测和事件配置之前 |
created | 实例创建完成,数据观测和事件配置之后 |
beforeMount | 挂载开始之前 |
mounted | 挂载完成之后 |
beforeUpdate | 数据更新前 |
updated | 数据更新后 |
beforeDestroy | 实例销毁前 |
destroyed | 实例销毁后 |
七、过渡 & 动画
<transition name="fade">
<p v-if="show">淡入淡出效果</p>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
八、Vue Router 路由系统
8.1 安装
npm install vue-router
8.2 配置路由
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './Home.vue';
import About from './About.vue';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
new Vue({
router
}).$mount('#app');
九、Vuex 状态管理
9.1 安装
npm install vuex
9.2 基本使用
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
}
});
new Vue({
store
});
十、Axios 网络请求
10.1 安装
npm install axios
10.2 基础使用
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
});
十一、进阶实战:Axios 封装
在项目中,推荐将 Axios 封装为独立模块,方便管理接口、处理全局错误等。
11.1 封装 http.js
// src/utils/http.js
import axios from 'axios';
const service = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
// 请求拦截器
service.interceptors.request.use(config => {
// 可在这里统一携带 token
// config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
return config;
}, error => {
return Promise.reject(error);
});
// 响应拦截器
service.interceptors.response.use(response => {
return response.data;
}, error => {
console.error('请求出错:', error);
alert(error.response?.data?.message || '请求失败');
return Promise.reject(error);
});
export default service;
11.2 使用封装
import http from '@/utils/http';
http.get('/users')
.then(data => {
console.log('用户数据:', data);
});
十二、进阶实战:路由守卫
Vue Router 支持全局、单个路由、组件内守卫,可用于权限控制。
12.1 添加守卫
// router/index.js
router.beforeEach((to, from, next) => {
const isLoggedIn = !!localStorage.getItem('token');
if (to.meta.requiresAuth && !isLoggedIn) {
next('/login');
} else {
next();
}
});
12.2 路由配置示例
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
十三、进阶实战:统一 API 管理
推荐将接口集中管理,避免硬编码。
13.1 封装 api.js
// src/api/user.js
import http from '@/utils/http';
export function getUserList() {
return http.get('/users');
}
export function login(data) {
return http.post('/login', data);
}
13.2 使用
import { getUserList } from '@/api/user';
getUserList().then(list => {
console.log('用户列表:', list);
});
十四、实战示例:TodoList
14.1 基本结构
<div id="app">
<input v-model="newTodo" @keyup.enter="addTodo">
<ul>
<li v-for="todo in todos">
{{ todo.text }}
<button @click="removeTodo(todo)">删除</button>
</li>
</ul>
</div>
14.2 Vue 逻辑
new Vue({
el: '#app',
data: {
newTodo: '',
todos: []
},
methods: {
addTodo() {
if (this.newTodo.trim()) {
this.todos.push({ text: this.newTodo });
this.newTodo = '';
}
},
removeTodo(todo) {
this.todos = this.todos.filter(t => t !== todo);
}
}
});
十五、功能拓展(含代码实现)
15.1 自定义指令
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
15.2 自定义过滤器
Vue.filter('capitalize', function (value) {
if (!value) return '';
return value.charAt(0).toUpperCase() + value.slice(1);
});
15.3 使用 Vue.extend 动态组件
const Profile = Vue.extend({
template: '<p>这是动态创建的组件</p>'
});
new Profile().$mount('#profile');
十六、优化与最佳实践
- 组件划分要清晰,职责单一
- 使用 v-show 替代 v-if,减少频繁销毁创建
- 慎用 v-html 防止 XSS
- 利用 keep-alive 缓存组件
- 结合 Vue Devtools 调试
十七、总结
Vue 2.0 是构建现代 Web 应用的强大工具。通过本篇文章,你掌握了从基础到进阶的 Vue 2 知识体系,并通过实际案例加深了理解。继续深入组件化开发、状态管理、性能优化,你就能在实际项目中游刃有余地使用 Vue 2!🚀
到这里,这篇文章就和大家说再见啦!我的主页里还藏着很多 篇 前端 实战干货,感兴趣的话可以点击头像看看,说不定能找到你需要的解决方案~
创作这篇内容花了很多的功夫。如果它帮你解决了问题,或者带来了启发,欢迎:
点个赞❤️ 让更多人看到优质内容
关注「前端极客探险家」🚀 每周解锁新技巧
收藏文章⭐️ 方便随时查阅
📢 特别提醒:
转载请注明原文链接,商业合作请私信联系
感谢你的阅读!我们下篇文章再见~ 💕