一、初识VUE3
二、再识VUE3-MVVM
三、VUE3数据代理
四、VUE3事件处理
五、VUE3计算属性
六、Vue3监视属性
七、VUE3过滤器
七、VUE3内置指令
九、VUE3组件
十、VUE3生命周期
监视属性
-
当被监视的属性变化时, 回调函数自动调用, 进行相关操作
-
监视的属性必须存在,才能进行监视
-
watch不仅能监视data的普通属性,也可以检测计算属性
-
new Vue时传入watch配置
<div id="root">
<h1> {{ info }}</h1>
<button @click="change">
切换
</button>
</div>
<script type="text/javascript">
const vm =new Vue({
data (){
return {
yn: false
}
},
methods: {
change() {
this.yn = !this.yn;
}
},
computed: {
info() {
return this.yn ? 'Y' : 'N';
}
},
watch: {
yn: {
handler(newValue, preValue) {
console.log('yn 被修改了');
console.log(`newValue: ${newValue}, preValue: ${preValue}`);
}
}
}
})
vm.$mount('#root')
</script>
- 通过vm.$watch监视
vm.$watch('yn',{
handler(newValue,preValue){
console.log('yn 被修改了');
console.log(`newValue: ${newValue}, preValue: ${preValue}`);
}
})
深度监视
<div id="root">
<button @click="numbers.d.e++">
e加一
</button>
</div>
<script type="text/javascript">
const vm =new Vue({
data (){
return {
numbers:{
a:1,
b:1,
d:{
e:2
}
}
}
}
})
vm.$mount('#root')
vm.$watch('numbers',{
deep: true, //监视多级结构的属性
handler(newValue,preValue){
console.log(' numbers 被修改了');
console.log(`newValue: ${newValue}, preValue: ${preValue}`);
}
})
</script>
#监视简写
//简写 (代价就是不能配置其他配置项deep immediate)
vm.$watch('isHot', function (newValue, preValue){
//this === vm
console.log(newValue, preValue);
})
computed vs watch
- computed能完成的功能,watch都可以完成
- watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作。
两个重要的小原则:
1.所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm 或 组件实例对象。
2.所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数等、Promise的回调函数),最好写成箭头函数,
这样this的指向才是vm 或 组件实例对象。