JavaScript作为Web开发的基石,经历了从jQuery到三大框架的演进历程。在React、Angular和Vue的竞争中,Vue以其渐进式架构、低学习曲线和卓越的性能脱颖而出。2023年State of JS报告显示,Vue的满意度高达89%,成为最受欢迎的前端框架之一。
本文将带你从JavaScript基础直达Vue高级应用,包含:
// 箭头函数
const sum = (a, b) => a + b;
// 解构赋值
const user = { name: 'John', age: 30 };
const { name, age } = user;
// 异步处理
async function fetchData() {
try {
const res = await fetch('/api/data');
return await res.json();
} catch (error) {
console.error('Fetch failed', error);
}
}
// 模块化
import utils from './helpers.js';
export default function() { /* ... */ }class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
class Developer extends Person {
constructor(name, language) {
super(name);
this.language = language;
}
code() {
return `${this.name} codes in ${this.language}`;
}
}
const dev = new Developer('Alice', 'JavaScript');
console.log(dev.code()); // "Alice codes in JavaScript"Vue的响应式系统基于ES6 Proxy实现:
// 简化版响应式实现
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
track(target, key); // 依赖收集
return Reflect.get(target, key);
},
set(target, key, value) {
Reflect.set(target, key, value);
trigger(target, key); // 触发更新
return true;
}
});
}
const state = reactive({ count: 0 });
state.count++; // 自动触发UI更新<template>
<div>
<!-- 文本插值 -->
<h1>{{ title }}</h1>
<!-- 属性绑定 -->
<img :src="avatarUrl" alt="Avatar">
<!-- 条件渲染 -->
<div v-if="isAdmin">Admin Panel</div>
<div v-else>User Dashboard</div>
<!-- 列表渲染 -->
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index + 1 }}. {{ item.name }}
</li>
</ul>
<!-- 事件处理 -->
<button @click="handleSubmit">Submit</button>
</div>
</template><template>
<div class="product-card">
<img :src="product.image" :alt="product.name">
<h3>{{ product.name }}</h3>
<p>Price: {{ formattedPrice }}</p>
<button @click="addToCart">Add to Cart</button>
</div>
</template>
<script>
export default {
props: {
product: {
type: Object,
required: true
}
},
computed: {
formattedPrice() {
return `$${this.product.price.toFixed(2)}`;
}
},
methods: {
addToCart() {
this.$emit('add-to-cart', this.product.id);
}
}
}
</script>
<style scoped>
.product-card {
border: 1px solid #eee;
border-radius: 8px;
padding: 16px;
max-width: 300px;
}
</style>通信方式 | 适用场景 | 代码示例 |
|---|---|---|
Props/Events | 父子组件通信 | <Child :data="parentData" @update="handleUpdate"> |
Provide/Inject | 跨层级组件 | provide('user', userObj) / const user = inject('user') |
Event Bus | 任意组件 | mitt.on('event', handler) / mitt.emit('event', data) |
Vuex/Pinia | 全局状态管理 | store.commit('SET_DATA', payload) |
// router.js
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/', component: Home },
{ path: '/products', component: ProductList },
{
path: '/product/:id',
component: ProductDetail,
props: true // 将路由参数作为props传递
},
{ path: '/cart', component: Cart, meta: { requiresAuth: true } }
];
const router = createRouter({
history: createWebHistory(),
routes
});
// 路由守卫
router.beforeEach((to, from) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
return { path: '/login', query: { redirect: to.fullPath } };
}
});// stores/cart.js
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
state: () => ({
items: [],
total: 0
}),
getters: {
itemCount: (state) => state.items.length,
hasItem: (state) => (id) => state.items.some(item => item.id === id)
},
actions: {
addItem(product) {
const existing = this.items.find(item => item.id === product.id);
if (existing) {
existing.quantity++;
} else {
this.items.push({ ...product, quantity: 1 });
}
this.calculateTotal();
},
calculateTotal() {
this.total = this.items.reduce(
(sum, item) => sum + (item.price * item.quantity), 0
);
}
}
});技术 | 实现方式 | 效果 |
|---|---|---|
懒加载 | <Suspense> + 动态导入 | 减少初始包大小 |
虚拟滚动 | vue-virtual-scroller | 优化长列表性能 |
代码分割 | Webpack splitChunks | 按需加载模块 |
缓存策略 | 组件keep-alive | 减少重复渲染 |
// 1. XSS防护
v-html="sanitizedHTML" // 配合DOMPurify使用
// 2. CSRF防护
axios.defaults.headers.common['X-CSRF-TOKEN'] = getCookie('csrf_token');
// 3. 输入验证
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(user.email)) {
throw new Error('Invalid email');
}重要资源:
最终建议:学习Vue的最佳方式是实践!从今天开始构建你的第一个Vue应用吧~!
扩展阅读:随着Vue 3.4的发布,新特性如v-model改进、性能提升30%的编译器优化,以及全新的Reactivity Transform语法糖,都值得继续深入探索。前端的世界日新月异,但Vue的简洁哲学永恒不变。
喜欢的朋友请记得点赞关注加收藏!!