独立的 computed 属性
输出一个只读的 响应式引用
<p>我是王俊凯,我今年{{ age }}, {{ addAge }}周岁</p>
<el-button @click="ageAddClick">年龄+</el-button>
<script lang="ts">
import {computed, ref} from "vue";
setup() {
const age = ref(18);
const addAge = computed(() => {
return +age.value + 1;
});
const ageAddClick = () => {
age.value += 1;
};
return {
age,
addAge,
ageAddClick
}
}
</script>
使用计算属性的setter
计算属性默认只有 getter,不过在需要时你也可以提供一个 setter:
import { computed, ref } from "vue";
const age = ref(18);
const addAge = computed({
get() {
return age.value + 1;
},
set(newval: number) {
return (age.value = newval + 1);
},
});
传参问题
<p>
我是{{ name }},我今年{{ age }}, {{ addAge }}周岁, 两倍年龄为:{{doubleAges(age)}}
</p>
<el-button @click="ageAddClick">年龄+</el-button>
<script lang="ts">
import {computed, ref} from "vue";
setup() {
const age = ref(18);
const addAge = computed(() => {
return +age.value + 1;
});
//传参
const doubleAges = computed(() => {
return function (age) {
return age * 2;
};
});
const ageAddClick = () => {
age.value += 1;
};
return {
age,
addAge,
doubleAges,
ageAddClick
}
}
</script>
写到这里了,你们凑合看吧
(\ _ /)
( * . *)
/>❤️