# 数据监听
# computed
<template>
<div class="hello">
姓
<input type="text" v-model="person.firstName" />
<br />
名
<input type="text" v-model="person.lastName" />
<br />
全
<span>{{ person.fullName }}</span>
</div>
</template>
<script>
import { computed } from "@vue/reactivity";
import { reactive } from "vue";
export default {
name: "Computed",
props: {
msg: String
},
setup() {
const person = reactive({
firstName: "Gauss",
lastName: "Zhou"
});
person.fullName = computed(() => {
return person.firstName + person.lastName;
});
return {
person
};
}
};
</script>
# watch
<template>
<div class="watch">
<h2>Watch</h2>
<p>{{ count }}</p>
<button @click="count++">count ++</button>
<hr />
<p>{{ msg }}</p>
<hr />
<p>{{ person }}</p>
<button @click="person.name += '~'">修改姓名</button>
<button @click="person.age += 1">增加年龄</button>
<button @click="person.job.salary += 1000">涨工资</button>
</div>
</template>
<script>
import { reactive, ref, watch } from "vue";
export default {
name: "Watch",
setup() {
let count = ref(0);
let msg = ref("msg");
let person = reactive({
name: "张三",
age: 18,
job: {
salary: 10000
}
});
watch(
[count, msg],
(newV, oldV) => {
console.log("sum is changed", newV, oldV);
},
{ immediate: true }
);
watch(person, (newV, oldV) => {
console.log("person is changed", newV, oldV);
});
watch(
() => person.age,
(newV, oldV) => {
console.log("person.age is changed", newV, oldV);
}
);
return {
count,
msg,
person
};
}
};
</script>
# watchEffect 新增
监听副作用
为了根据响应式状态自动应用和重新应用副作用,我们可以使用 watchEffect 函数。它立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。
下面这个例子中,当 count 变化的时候,watchEffect 就会执行
<script>
import { reactive, ref, watch, watchEffect } from "vue";
export default {
name: "Watch",
setup() {
let count = ref(0);
let msg = ref("msg");
let person = reactive({
name: "张三",
age: 18,
job: {
salary: 10000
}
});
watchEffect(() => {
console.log(count.value);
console.log("watchEffect");
});
return {
count,
msg,
person
};
}
};
</script>
一种简单的理解是认为 watchEffect 是 computed 版的 watch