日期:2026年9月26日标签:JavaScript

Vue3 cheatsheet for reacter #

组件定义 #

react:

function Hello({ name }) {
  return <h1>Hello {name}</h1>;
}

vue:

<script setup>
defineProps({ name: String })
</script>
<template>
  <h1>Hello {{ name }}</h1>
</template>

props #

react:

function Component({ title }) { 
    //...
}

vue:

<script setup>
const props = defineProps({ title: String })
</script>

state #

react:

const [count, setCount] = useState(0)

vue:

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

计算属性 #

react:

const double = useMemo(() => count * 2, [count])

vue:

<script setup>
const double = computed(() => count.value * 2)
</script>

生命周期 #

vue:

  • onMounted: react 的 componentDidMount
  • onUpdated: react 的 componentDidUpdate
  • onUnmounted: react 的 componentWillUnmount
  • watch:react 的 useEffect

事件处理 #

react:

<button onClick={handleClick}>Click</button>

vue:

<button @click="handleClick">Click</button>

条件渲染、列表渲染 #

react:

// conditional render
{show && <Component />}

// list render
{items.map(item => <li key={item.id}>{item.label}</li>)}

vue:

// conditional render
<Component v-if="show" />

// list render
<li v-for="item in items" :key="item.id">
  {{ item.label }}
</li>

双向绑定 #

react:

<input value={text} onChange={e => setText(e.target.value)} />

vue:

<input v-model="text" />

父子组件通信 #

react:

// 父组件直接将方法传递给子组件调用
onSelect(value)

vue:

// 子组件 emit
<script setup>
const emit = defineEmits(['select'])
</script>

<button @click="emit('select', 123)">
  Select
</button>

// 父组件 监听
<Child @select="handleSelect" />

(完)

目录