[{"data":1,"prerenderedAt":224},["ShallowReactive",2],{"content:\u002Fposts\u002F2025\u002Fgood-practices-for-vue-computed-properties":3,"surround:\u002Fposts\u002F2025\u002Fgood-practices-for-vue-computed-properties":213},{"id":4,"title":5,"body":6,"canonical":16,"categories":192,"date":194,"description":25,"draft":195,"extension":196,"image":197,"meta":198,"navigation":199,"path":200,"permalink":201,"readingTime":202,"recommend":207,"references":201,"seo":208,"sitemap":209,"stem":210,"tags":211,"type":201,"updated":194,"__hash__":212},"content\u002Fposts\u002F2025\u002Fgood-practices-for-vue-computed-properties.md","【翻译】Vue 计算属性的良好实践",{"type":7,"value":8,"toc":178},"minimark",[9,20,23,26,29,32,37,40,43,54,69,72,75,80,83,86,94,97,103,107,110,112,118,120,126,130,133,139,143,146,152,156,159,165,169,172,175],[10,11,12,13],"p",{},"原文地址：",[14,15,19],"a",{"href":16,"rel":17},"https:\u002F\u002Fdev.to\u002Fjacobandrewsky\u002Fgood-practices-for-vue-computed-properties-5gd7",[18],"nofollow","Good practices for Vue Computed Properties",[21,22],"hr",{},[10,24,25],{},"计算属性是 Vue 中的一个强大功能，允许您根据响应式状态动态推导和转换数据。当正确使用时，它们可以使您的代码更简洁、更高效、更易于维护。然而，不当的使用可能会导致意外的错误和性能问题。",[10,27,28],{},"在这篇文章中，我们将介绍在 Vue 中使用计算属性的良规，确保您能充分利用它们:)",[10,30,31],{},"Enjoy！",[33,34,36],"h2",{"id":35},"什么是计算属性","🤔什么是计算属性？",[10,38,39],{},"计算属性是 Vue 中的特殊属性，当它们的依赖项发生变化时自动更新。与方法不同，它们在依赖项变化之前被缓存，这使得它们成为派生状态的效率选择。",[10,41,42],{},"让我们看看以下基本示例：",[44,45,51],"pre",{"className":46,"code":48,"language":49,"meta":50},[47],"language-vue","\u003Cscript setup lang=\"ts\">\nimport { computed, ref } from 'vue';\n\nconst firstName = ref('John');\nconst lastName = ref('Doe');\n\nconst fullName = computed(() => `${firstName.value} ${lastName.value}`);\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n    \u003Cdiv>\n        \u003Cp>Full Name: {{ fullName }}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n","vue","",[52,53,48],"code",{"__ignoreMap":50},[10,55,56,57,60,61,64,65,68],{},"这里， ",[52,58,59],{"code":59},"fullName"," 在 ",[52,62,63],{"code":63},"firstName"," 或 ",[52,66,67],{"code":67},"lastName"," 发生变化时自动更新，无需手动重新计算。",[33,70,71],{"id":71},"计算属性的良好实践",[10,73,74],{},"正如我们已了解 Vue 计算属性是什么，现在让我们深入了解一些良好实践。",[76,77,79],"h3",{"id":78},"_1-使用计算属性进行派生状态","1. 使用计算属性进行派生状态",[10,81,82],{},"避免使用计算属性直接操作或设置状态。相反，保留它们用于基于现有状态的计算或转换。",[10,84,85],{},"GOOD:",[44,87,92],{"className":88,"code":90,"language":91,"meta":50},[89],"language-ts","const cartItems = ref([{ price: 10 }, { price: 15 }]);\nconst totalPrice = computed(() => cartItems.value.reduce((sum, item) => sum + item.price, 0));\n","ts",[52,93,90],{"__ignoreMap":50},[10,95,96],{},"BAD:",[44,98,101],{"className":99,"code":100,"language":91,"meta":50},[89],"const cartItems = ref([]);\nconst addItem = computed(() => item => cartItems.value.push(item));\n\u002F\u002F Use a method for state modification instead\n",[52,102,100],{"__ignoreMap":50},[76,104,106],{"id":105},"_2-避免计算属性中的副作用","2. 避免计算属性中的副作用",[10,108,109],{},"计算属性应保持纯净且无副作用。这确保它们是可预测的，并且仅用于计算值。",[10,111,85],{},[44,113,116],{"className":114,"code":115,"language":91,"meta":50},[89],"const items = ref([1, 2, 3]);\nconst doubledItems = computed(() => items.value.map(item => item * 2));\n",[52,117,115],{"__ignoreMap":50},[10,119,96],{},[44,121,124],{"className":122,"code":123,"language":91,"meta":50},[89],"const items = ref([1, 2, 3]);\nconst doubledItems = computed(() => {\n    console.log('Doubled items calculated'); \u002F\u002F Side effect\n    return items.value.map(item => item * 2);\n});\n",[52,125,123],{"__ignoreMap":50},[76,127,129],{"id":128},"_3-缓存昂贵计算","3. 缓存昂贵计算",[10,131,132],{},"计算属性的主要优点之一是其缓存机制。利用这一点进行昂贵计算，以避免不必要的重新计算。",[44,134,137],{"className":135,"code":136,"language":91,"meta":50},[89],"const largeData = ref([...Array.from({ length: 1000000 }).keys()]);\nconst sum = computed(() => largeData.value.reduce((a, b) => a + b, 0));\n",[52,138,136],{"__ignoreMap":50},[76,140,142],{"id":141},"_4-为双向计算属性使用-getter-和-setter","4. 为双向计算属性使用 getter 和 setter",[10,144,145],{},"当你需要一个既可以计算属性也可以设置值的属性时，请使用 getter 和 setter。这对于影响其他响应式数据的派生状态非常有用。",[44,147,150],{"className":148,"code":149,"language":49,"meta":50},[47],"\u003Cscript setup lang=\"ts\">\nimport { computed, ref } from 'vue';\n\nconst firstName = ref('John');\nconst lastName = ref('Doe');\n\nconst fullName = computed({\n    get: () => `${firstName.value} ${lastName.value}`,\n    set: (newValue) => {\n        const [first, last] = newValue.split(' ');\n        firstName.value = first;\n        lastName.value = last;\n    }\n});\n\u003C\u002Fscript>\n\n\u003Ctemplate>\n    \u003Cinput v-model=\"fullName\">\n    \u003Cp>Full Name: {{ fullName }}\u003C\u002Fp>\n\u003C\u002Ftemplate>\n",[52,151,149],{"__ignoreMap":50},[76,153,155],{"id":154},"_5-分解复杂计算属性","5. 分解复杂计算属性",[10,157,158],{},"为了可读性和可维护性，避免过度复杂的计算属性。如有必要，将其拆分为更小、可重用的部分。",[44,160,163],{"className":161,"code":162,"language":91,"meta":50},[89],"const basePrice = ref(100);\nconst tax = ref(0.1);\n\nconst priceWithTax = computed(() => basePrice.value * (1 + tax.value));\nconst formattedPrice = computed(() => `$${priceWithTax.value.toFixed(2)}`);\n",[52,164,162],{"__ignoreMap":50},[33,166,168],{"id":167},"摘要","✅ 摘要",[10,170,171],{},"计算属性是 Vue 中管理派生状态的有效工具。通过遵循最佳实践，如避免副作用、利用缓存和分解复杂逻辑，您可以确保您的应用程序保持高性能和可维护性。从今天开始应用这些技巧，编写更干净、更健壮的 Vue 组件！",[10,173,174],{},"请注意，下次再见！",[10,176,177],{},"And happy coding as always 🖥️",{"title":50,"searchDepth":179,"depth":179,"links":180},4,[181,183,191],{"id":35,"depth":182,"text":36},2,{"id":71,"depth":182,"text":71,"children":184},[185,187,188,189,190],{"id":78,"depth":186,"text":79},3,{"id":105,"depth":186,"text":106},{"id":128,"depth":186,"text":129},{"id":141,"depth":186,"text":142},{"id":154,"depth":186,"text":155},{"id":167,"depth":182,"text":168},[193],"译","2025-01-28 17:56:14",false,"md","https:\u002F\u002Fbitmc.uno\u002Fpicgo\u002Fgood-practices-for-vue-computed-properties.jpg",{},true,"\u002Fposts\u002F2025\u002Fgood-practices-for-vue-computed-properties",null,{"text":203,"minutes":204,"time":205,"words":206},"5 min read",4.14,248400,828,1,{"title":5,"description":25},{"loc":200},"posts\u002F2025\u002Fgood-practices-for-vue-computed-properties",[],"_j-mc2c0TLoKsQgP8CB0GIpedflCRIeYIrcR8Qn1K2Q",[214,219],{"title":215,"path":216,"stem":217,"date":218,"type":201,"children":-1},"如何让网站图标跟随系统主题变化？","\u002Fposts\u002F2025\u002Fhow-to-dynamically-change-favicon-for-dark-and-light-mode","posts\u002F2025\u002Fhow-to-dynamically-change-favicon-for-dark-and-light-mode","2025-01-22 13:49:51",{"title":220,"path":221,"stem":222,"date":223,"type":201,"children":-1},"乙巳年除夕记","\u002Fposts\u002F2025\u002F2025-nongli-new-year","posts\u002F2025\u002F2025-nongli-new-year","2025-01-28 23:23:01",1789642585198]