1.vue3对比vue2生命周期钩子函数:
2.vue3中的watch:
<template>
<p>{{count}}</p>
<p>{{double}}</p>
<button @click="increase">👍</button>
<p>{{greeting}}</p>
<button @click="greetingValue">UpdateGreeting</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import {ref,computed,reactive,toRefs,watch} from "vue";
interface DataProps {
count:number;
double:number;
increase:() => void;
}
export default defineComponent({
name: 'App',
setup(){
const data:DataProps = reactive({
count:0,
increase:()=>{
data.count++;
},
double:computed(()=>{
return data.count * 2
})
})
const refData = toRefs(data);
const greeting = ref("");
const greetingValue = ()=>{
greeting.value += "Go~!";
}
//通过watch监听
watch([greeting,data],(newVal,oldVal)=>{
document.title = "updated" + greeting.value + data.count;
})
return {
...refData,greeting,greetingValue
}
}
});
</script>
watch的使用方式:
- 第一种:监听
ref创建的简单数据类型:
watch(greeting,(newVal,oldVal)=>{
document.title = "updated" + greeting.value
}
- 第二种:监听
reactive创建的数据中的某个值:
watch([greeting,data],(newVal,oldVal)=>{
console.log(newVal);
console.log(oldVal)
document.title = "updated" + greeting.value + data.count;
})
直接用如下代码监听data,控制台会出现:
那么如何监听到data.count?
- 通过
箭头函数,返回一个需要watch的字段,这里是data.count
watch([greeting,()=>data.count],(newVal,oldVal)=>{
console.log(newVal);
console.log(oldVal);
document.title = "updated" + greeting.value + data.count;
})
上面可以看到监听的结果不再是一个proxy,而是值0,2,1,3,2,4,3....