Skip to content

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 对比

特性VueReact
模板语法模板 + 指令JSX
响应式自动追踪手动声明(Hooks)
学习曲线平缓较陡
生态官方维护完整社区丰富

基于 MIT 许可发布