Vue 比 React 更合我心意的地方
我用 React 很久了,所以当有人说“嘿,你应该试试别的前端框架”时,我总是嗤之以鼻,心想我已经很高效了 =P。不过,Vue 最近发展得相当不错,让我很想尝试一下。结果真是让我惊喜!Vue 有很多很棒的功能,让我这个 React 开发者羡慕不已。接下来,我们就来深入探讨一下 Vue 的一些模式,看看它们是如何区别于 React 的!
1. 安装很有趣
Vue 的开箱即用体验远胜于 CRA——npm create vue@latest感觉像是精心设计的,而npm create-react-appCRA 只是一条普通的 NPM 命令。我更喜欢 Vue 那种交互式地选择要安装的包的方式,而不是 CRA 的那种流程。
此外,Vue 安装的软件包比 CRA 提供了更完整的开发体验,涵盖了路由、状态管理和代码格式化等领域。
Vue 的安装过程非常人性化。
localhost另外,我们能不能聊聊当你打开新项目时,起始页面有多么实用?
今后所有的 Vue 示例都将使用 Vue 3 中的 Composition API,这与函数式 React 最为相似。
2. 直观的反应系统
与 React 的状态管理相比,Vue 的响应式系统更加直观,样板代码也更少。Vue 会自动处理依赖项跟踪和更新,使状态管理变得简单直接。
Vue 示例
<template>
<p>{{ count }}</p>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const count = ref(0);
onMounted(() => {
setInterval(() => {
count.value++;
}, 1000);
});
onUnmounted(() => clearInterval(interval));
</script>
React 等效项
React 需要编写更多样板代码才能实现类似的响应式,尤其是在处理依赖于先前状态值的 effects 和状态更新时。每次想用它们的时候useEffect,是不是都要去查 `$( ... ))))`)`useMemo和`$($($($($($($($($($($($))))`)`)`)` 之间的细微差别?🙋🏾♂️useCallback
function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
setCount(currentCount => currentCount + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>{count}</p>;
}
3. 单文件组件
单文件组件(SFC)确实褒贬不一,但我认为它们很棒,尤其适用于小型组件。在我看来,将 HTML、JavaScript 和 CSS 封装在一个文件中,有助于提高代码的组织性和可读性。
Vue 单文件组件
<script setup lang="ts">
import { defineProps } from 'vue'
defineProps({
message: String
})
</script>
<template>
<div class="message-box">
<p>{{ message }}</p>
</div>
</template>
<style scoped>
.message-box {
padding: 20px;
border: 1px solid #eee;
}
</style>
React 等效项
在 React 中,实现同样的封装通常需要将关注点分离到不同的文件中,或者采用 CSS-in-JS 库,但这会增加复杂性。
function MessageBox({ message }) {
return (
<div className="message-box">
<p>{message}</p>
</div>
);
}
// CSS is managed separately or through CSS-in-JS solutions
4. 条件渲染
Vue 的指令系统(例如v-if`<if>` v-for、`<else>` 等)在条件渲染方面比 React 更易读。当 if/else 语句变得更加复杂时,这种优势就更加明显了。
Vue指令示例
<script setup lang="ts">
import { ref } from 'vue';
const isSubscribed = ref(false);
const isSubscriptionExpiring = ref(true);
// Above properties updated dynamically...
</script>
<template>
<div>
<p v-if="!isSubscribed">Please subscribe to access premium features.</p>
<p v-else-if="isSubscriptionExpiring">Your subscription is expiring soon. Please renew to continue enjoying premium features.</p>
<p v-else>Welcome back, valued premium user!</p>
</div>
</template>
React 等效项
function SubscriptionStatus() {
const isSubscribed = false;
const isSubscriptionExpiring = true;
// Above properties updated dynamically...
return (
<div>
{isSubscribed ? (
isSubscriptionExpiring ? (
<p>Your subscription is expiring soon. Please renew to continue enjoying premium features.</p>
) : (
<p>Welcome back, valued premium user!</p>
)
) : (
<p>Please subscribe to access premium features.</p>
)}
</div>
);
}
当然,你可以将基于 JSX 的逻辑移到一个 JS 函数中,但在 Vue 中,初始传递更容易理解。
5. 计算属性
Vue 的计算属性简化了依赖于响应式数据的复杂逻辑的处理。它们会被自动缓存,并且仅在依赖项发生变化时才重新计算,从而优化性能。
Vue 示例
<script setup lang="ts">
import { computed, ref } from 'vue'
const price = ref(10)
const quantity = ref(3)
const totalPrice = computed(() => price.value * quantity.value)
</script>
<template>
<p>Total price: {{ totalPrice }}</p>
</template>
React 等效项
在 React 中,类似的功能需要 useMemo hook,这会增加组件逻辑的复杂性和冗长性。
function TotalPrice() {
const [price, setPrice] = React.useState(10);
const [quantity, setQuantity] = React.useState(3);
const totalPrice = React.useMemo(() => {
return price * quantity;
}, [price, quantity]);
return <p>Total price: {totalPrice}</p>;
}
6. 精简的州管理
Pinia 是 Vue 推荐的状态管理解决方案之一。由于它与 Vue 的紧密集成和精心设计的 API,它比 React + Redux 中同等功能的代码更加精简高效。
Vue with Pinia
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
actions: {
increment() {
this.count++
},
},
})
// components/MyCounter.vue
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">Increment</button>
<div>Current Count: {{ counter.count }}</div>
</template>
React 与 Redux
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1
}
},
})
export const { increment } = counterSlice.actions
export default counterSlice.reducer
// Counter.js
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment } from './counterSlice'
export function Counter() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<button onClick={() => dispatch(increment())}>
Increment
</button>
<span>{count}</span>
)
}
综上所述
我初次接触 Vue 的经历拓宽了我对优秀设计模式和良好 API 构建的理解。很明显,Vue 从第一个版本开始就将开发者体验和应用性能放在首位。我认为这里最大的启示是:无论你的技能水平如何,无论你精通哪些工具,尝试新事物总能让你有所收获!
你还喜欢Vue的哪些方面?请在评论区告诉我!
PS:我每周会分享两次类似这样的内容。如果你对前端、后端以及如何成为一名更优秀的全栈开发者感兴趣, 请订阅我的邮件列表!
文章来源:https://dev.to/jaydevm/things-that-i-like-better-in-vue-than-in-react-56o3

