1.computed:当依赖的值发生修改时,执行的方法,如果未发生改变,则使用缓存的值
函数的形式:
<template> <div>{{ obj.name }}</div> <div>{{ obj.age }}</div> <div>{{ age }}</div> </template> <script setup lang="ts"> import { reactive, computed } from 'vue'; let obj = reactive({ name: '张三', age: 18 }); let age = computed(() => { return '今年:' + obj.age; }); obj.age++; </script>
对象的形式:
<template> <div>{{ obj.name }}</div> <div>{{ obj.age }}</div> </template> <script setup lang="ts"> import { reactive, computed } from 'vue'; let obj = reactive({ name: '张三', age: 18 }); let age = computed({ get: () => { return obj.age; }, set: (newVal) => { obj.age = newVal; } }); obj.age++; </script>