vue官方推薦使用計算屬性來描述依賴響應式狀態的復雜邏輯,computed具有緩存的作用,一個計算屬性僅會在其響應式依賴更新時才重新計算,這意味著只要 相關值?不改變,無論多少次訪問?都會立即返回先前的計算結果,從而在一定程度上提升性能。
使用示例:
使用前需引入:
import {computed} from "vue"
<template><view class="out"><input type="text" v-model="firstName" placeholder="請輸入名字" /><input type="text" v-model="lastName" placeholder="請輸入姓氏" /><view>全稱:{{fullName}}</view></view>
</template><script setup>import {ref,computed} from "vue"const firstName=ref("")const lastName=ref("")const fullName = computed(()=>firstName.value+"·"+lastName.value)
</script><style lang="scss" scoped>.out{padding:20px;input{height: 40px;border: 1px solid #ccc;margin: 10px 0;padding: 0 10px;}}
</style>
當computed要執行的代碼比較簡單時,可簡寫為上面的箭頭函數的方式。computed在一定程度上跟ref相似,所不同的ref可重新賦值,而computed的變量為可讀,最好不要去修改computed的變量的值,computed和函數實現的效果完全相同,兩者的區別主要體現在函數沒有緩存,每次都會執行,而computed在滿足條件時會讀取緩存而不重復執行。