当前位置: 首页 > ai >正文

Vue 2.0 详解全教程(含 Axios 封装 + 路由守卫 + 实战进阶)

目录

  • 一、Vue 2.0 简介
    • 1.1 什么是 Vue?
    • 1.2 Vue 2.x 的主要特性
  • 二、快速上手
    • 2.1 引入 Vue
    • 2.2 创建第一个 Vue 实例
  • 三、核心概念详解
    • 3.1 模板语法
    • 3.2 数据绑定
    • 3.3 事件绑定
    • 3.4 计算属性 & 侦听器
  • 四、组件系统
    • 4.1 定义全局组件
    • 4.2 单文件组件(*.vue 文件)
    • 4.3 父子组件通信
  • 五、指令系统
  • 六、生命周期钩子
  • 七、过渡 & 动画
  • 八、Vue Router 路由系统
    • 8.1 安装
    • 8.2 配置路由
  • 九、Vuex 状态管理
    • 9.1 安装
    • 9.2 基本使用
  • 十、Axios 网络请求
    • 10.1 安装
    • 10.2 基础使用
  • 十一、进阶实战:Axios 封装
    • 11.1 封装 http.js
    • 11.2 使用封装
  • 十二、进阶实战:路由守卫
    • 12.1 添加守卫
    • 12.2 路由配置示例
  • 十三、进阶实战:统一 API 管理
    • 13.1 封装 api.js
    • 13.2 使用
  • 十四、实战示例:TodoList
    • 14.1 基本结构
    • 14.2 Vue 逻辑
  • 十五、功能拓展(含代码实现)
    • 15.1 自定义指令
    • 15.2 自定义过滤器
    • 15.3 使用 Vue.extend 动态组件
  • 十六、优化与最佳实践
  • 十七、总结


一、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!🚀


到这里,这篇文章就和大家说再见啦!我的主页里还藏着很多 篇 前端 实战干货,感兴趣的话可以点击头像看看,说不定能找到你需要的解决方案~
创作这篇内容花了很多的功夫。如果它帮你解决了问题,或者带来了启发,欢迎:
点个赞❤️ 让更多人看到优质内容
关注「前端极客探险家」🚀 每周解锁新技巧
收藏文章⭐️ 方便随时查阅
📢 特别提醒:
转载请注明原文链接,商业合作请私信联系
感谢你的阅读!我们下篇文章再见~ 💕

在这里插入图片描述

http://www.xdnf.cn/news/4197.html

相关文章:

  • OpenCV 图形API(78)图像与通道拼接函数-----调整图像大小的函数resize()
  • C# 方法(值参数和引用参数)
  • mysql 如何查询数据库链接日志
  • Spring 中四种常见初始化方法,对比 static {} 和 @PostConstruct 在并发,Spring 加载顺序大致为: JVM 加载类
  • 生成了一个AI算法
  • 网络安全的范式革命:从被动防御到 AI 驱动的主动对抗
  • 基于大模型的自然临产阴道分娩全流程预测与方案研究报告
  • 开个帖子记录一下自己学spring源码的过程
  • Spyglass:官方Hands-on Training(三)
  • 数据中台架构设计
  • c++类【发展】
  • 【全面解析】Poco C++ Libraries 模块详解与使用指南
  • UE5 使用插件进行Audio2face和UE5的实时链接并实时输出嘴型
  • 多模态训练与微调
  • 突破v0.dev对话限制的两种方法
  • k8s node 报IPVS no destination available
  • 19.第二阶段x64游戏实战-vector容器
  • 二叉树的最大深度(简单)
  • 标题:基于自适应阈值与K-means聚类的图像行列排序与拼接处理
  • LintCode第484题-交换数组两个元素,第9题-Fizz Buzz 问题,第46题-主元素,第50题数组剔除元素后的乘积
  • 超表面加工流程
  • 从零开始了解数据采集(二十二)——塑胶制品行业趋势分析案例
  • (leetcode) 力扣100 6.三数之和 (双指针)
  • 卷积神经网络的简单实战项目
  • 大模型——GraphRAG基于知识图谱+大模型技术构建的AI知识库系统
  • 怎样用 esProc 实现多数据库表的数据合并运算
  • 深入理解 Linux 阻塞IO与Socket数据结构
  • 《脑机接口与AI:如何让瘫痪患者用“意念”实现创作?》
  • 在 PyTorch 中借助 GloVe 词嵌入完成情感分析
  • 【Vue】组件自定义事件 TodoList 自定义事件数据传输