Q Code

遇事不决 可问春风 春风不语 遵循自心

vue3之computed和watch

在vue3中正确使用computedwatch的方式是什么呢?

computed

在vue3中,computed也是支持以组合式API的形式来使用的,

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
<template>
<div>
<input type="number" v-model="obj.first">+
<input type="number" v-model="obj.second">=
{{sum}}<br>
</div>
</template>

<script>
import {reactive,computed} from 'vue'
export default {
setup(){
const obj = reactive({
first: 0,
second: 0
})
const sum =computed(()=>{
return obj.first + obj.second
})
return {
obj,
sum
}
}
}
</script>

上面是我们常用的计算属性取值的简单示例。那对于修改该怎么办呢?

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

<template>
<div class="home">
姓:<input type="text" v-model="names.familyName"><br>
名:<input type="text" v-model="names.lastName"><br>
姓名:<input type="text" v-model="names.fullName"><br>
</div>
</template>

<script>
import {reactive,computed} from 'vue'
export default {
name: 'Home',
setup(){
const names = reactive({
familyName:'张',
lastName:'三'
});
names.fullName = computed({
get(){
return names.familyName + '.' + names.lastName;
},
set(value){
const arr = value.split('.')
names.familyName = arr[0];
names.lastName = arr[1];
}
})
return {
names
};
}
}
</script>

watch

对于watch,同样也是组合式API不多说,直接看🌰
1.对于ref数据

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
<template>
<div>
<button @click="n++">N++</button>
<P>{{ n }}</P>
<button @click="() => {
a++;
b++;
}">a,b ++</button>

</div>
</template>

<script>
import { ref, watch } from 'vue';
export default {
setup(){
let n = ref(1);

watch(n, (newValue, oldValue) => {
console.log(newValue, oldValue);
});


let a, b = 1;
// 监听多个
watch([a, b], (newValue, oldValue) = > {
// 此时newValue, newValue同样也是数组
console.log(newValue, newValue);
});
return {
n
};
}
}
</script>

2.对于reactive,综合🌰

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
<template>
<div>
<p>年龄{{obj.age}}</p>
<p>身高{{obj.height}}</p>
<button @click="() => {
obj.age++;
obj.height--;
}">change</button>
</div>
</template>

<script>
import { ref, watch } from 'vue';
export default {
setup(){
const obj = reactive({
age: 18,
height: 188
});

// 立即执行,监听多个数据
watch([() => obj.age, () => obj.height], (newV, oldV) => {
console.log(newV, oldV);
}, {
immediate: true
});
return {
n
};
}
}
</script>

watchEffect

watchEffect是vue3中新增加的函数

官方解释:立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数
简单总结下和watch,computed的优势和区别

  1. 自动开始了immediate: true
  2. 追踪依赖,用到了谁就监视谁
  3. computed相比不用写返回值
    1
    2
    3
    4
    5
    6

    watchEffect(() => {
    const age = obj.age;
    const height = cur.height;
    console.log(age, height, "改变了~");
    });