vue3 setup 計算屬性 computed - 例項計數器
阿新 • • 發佈:2022-04-14
<script> // computed 計算屬性 const app = Vue.createApp({ setup() { // 引入計算屬性 const { reactive, computed } = Vue; const countObj = reactive({ count: 0}); // 定義函式 每次計數器 + 1 const handleClick = () => { countObj.count += 1; } // 獲取(更新): 返回值:countAddfive + 5 , 設定: 設定countObj.count 值為 --5View Codelet countAddFive = computed({ get: () => { return countObj.count + 5; }, set: (param) => { countObj.count = param - 5; } }) setTimeout(() => { // 這裡相當於 設定value 的值, set(100) ,然後100 - 5 = 95 所以 countObj.count 值為 95 countAddFive.value = 100; },3000) return { countObj, countAddFive, handleClick } }, // {{countAddFive}} 讀取了 countAddFive的值,返回了 countObj.count + 5; ,所以直接點選的時候 就讀取(更新)了一次,每次都返回 countObj.count 加 5 , template: ` <div> <span @click="handleClick">{{countObj.count}}</span> -- {{countAddFive}} </div> `, }); const vm= app.mount('#root'); </script>
截圖:
3S後:
點選觸發 handleClick 函式:
countObj.count += 1; 然後 countAddFive 跟著重新整理,,,然後觸發計算屬性的get方法,然後 countObj.count + 5; 其實就是加了1而已,因為 101 - 96 = 5 :
完.