vue3中使用computed与watch

#tag

vue3中使用computed与watch的笔记

computed

注意点:返回的是一个ref对象

  • 函数的话,返回是一个readOnly的ref对象
  • 对象的话,需要设置set方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<div>
<h1>ComputedAndWatch Study Vue3</h1>
<p>{{ computedInfo }}</p>
<button @click="changeComputedInfo">change computed info</button>
</div>
</template>

<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const info = reactive({
name: 'Hbisedm',
age: 23,
})
// const computedInfo = computed(() => {
// return `${info.name}-${info.age}`
// })
const computedInfo = computed({
get() {
return `${info.name}-${info.age}`
},
set(newVal) {
const arr = newVal.split('-')
info.name = arr[0]
info.age = arr[1]
}
})
const changeComputedInfo = () => {
computedInfo.value = 'CoderSam-24'
}
return {
computedInfo,
changeComputedInfo
}
}
}
</script>

watch

watchEffect

watch



本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!