这是我参与11月更文挑战的第4天,活动详情查看:11月更文挑战
在vue3中正确使用computed
和watch
的方式是什么呢?
computed
在vue3中,
computed
也是支持以组合式API
的形式来使用的,
<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>
上面是我们常用的计算属性取值的简单示例。那对于修改该怎么办呢?
<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
数据
<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
,综合🌰
<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
的优势和区别
- 自动开始了
immediate: true
- 追踪依赖,用到了谁就监视谁
- 和
computed
相比不用写返回值
watchEffect(() => {
const age = obj.age;
const height = cur.height;
console.log(age, height, "改变了~");
});