【笔记】Vue3的计算属性

前言

Vue3的计算属性学习笔记

OptionsAPI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
{{ key }}
</template>

<script>
export default {
data: function () {
return {
internalKey: "value"
}
},
computed: {
key: {
get: function () {
return this.internalKey;
},
set: function (value) {
this.internalKey = value;
}
}
}
}
</script>

CompositionAPI

  • 计算属性使用ref进行包裹,所以使用时需要手动解包

setup函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
import { computed } from "vue"

export default {
setup: function (attrs, slots, emit) {
const key = computed({
set: function (newValue) {
console.log(newValue);
},
get: function () {
return "value";
}
});

// 手动解包
console.log(key.value);

return {
key
};
}
}
</script>
  • 简写,只包含get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
import { computed } from "vue"

export default {
setup: function (attrs, slots, emit) {
const key = computed(() => {
return "value";
});

key.value += "1";

return {
key
};
}
}
</script>

完成