vue3 setup 计算属性 computed - 实例计数器
作者:互联网
<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 值为 --5 let 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>View Code
截图:
3S后:
点击触发 handleClick 函数:
countObj.count += 1; 然后 countAddFive 跟着刷新,,,然后触发计算属性的get方法,然后 countObj.count + 5; 其实就是加了1而已,因为 101 - 96 = 5 :
完.
标签:count,countObj,computed,handleClick,setup,vue3,const,countAddFive 来源: https://www.cnblogs.com/bi-hu/p/16143213.html