Vue & React
Vue.js
基础示例
vue
<template>
<div>
<h1>{{ message }}</h1>
<button @click="increment">Count: {{ count }}</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = 'Hello Vue!'
const count = ref(0)
const increment = () => count.value++
</script>核心概念
- 响应式系统 - ref / reactive
- 计算属性 - computed
- 侦听器 - watch
- 生命周期 - onMounted / onUnmounted
- 组件通信 - Props / Emits / Provide / Inject
Vuex/Pinia 状态管理
javascript
// Pinia 示例
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ }
}
})React
函数组件
jsx
import { useState, useEffect } from 'react'
function Counter() {
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `Count: ${count}`
}, [count])
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
+
</button>
</div>
)
}核心 Hooks
useState- 状态管理useEffect- 副作用处理useContext- 上下文useCallback/useMemo- 性能优化
Redux 状态管理
javascript
import { createSlice, configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1 }
}
})Vue vs React 对比
| 特性 | Vue | React |
|---|---|---|
| 模板语法 | 模板 + 指令 | JSX |
| 响应式 | 自动追踪 | 手动声明(Hooks) |
| 学习曲线 | 平缓 | 较陡 |
| 生态 | 官方维护完整 | 社区丰富 |