0
点赞
收藏
分享

微信扫一扫

20.Vue监视的简写形式

南柯Taylor 2022-09-21 阅读 198


前两节我们讲了Vue的监视属性及深度监视,这一节我们来写一下监视的简写形式:

注意:只有当watch的配置中只有handler而没有其他配置时才可以使用简写形式

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>天气案例_深度监视</title>
<!--引入Vue-->
<script type="text/javascript" src="../js/vue.js"></script>
<style>

</style>
</head>
<body>
<!--准备好一个容器-->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click = "changeWeather">切换天气</button>

</div>
</body>

<script type="text/javascript">
Vue.config.productionTip = false //阻止Vue在启动时生成生产提示
const vm = new Vue({
el:'#root',
data:{
isHot:true

},
computed:{
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods:{
changeWeather(){
this.isHot = !this.isHot
}
},
watch:{
//正常写法
/* isHot:{
immediate:true, //初始化的时候让handler调用一下
deep:true, //深度监视
//handler什么时候调用?当isHot发生改变时
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
} */
//简写
isHot(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}

}
})

</script>
</html>

实现效果:

20.Vue监视的简写形式_javascript

我们之前说过监视还有一种vm.$watch的写法,那如果是这种方式该怎么简写呢?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>天气案例_深度监视</title>
<!--引入Vue-->
<script type="text/javascript" src="../js/vue.js"></script>
<style>

</style>
</head>
<body>
<!--准备好一个容器-->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click = "changeWeather">切换天气</button>

</div>
</body>

<script type="text/javascript">
Vue.config.productionTip = false //阻止Vue在启动时生成生产提示
const vm = new Vue({
el:'#root',
data:{
isHot:true

},
computed:{
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods:{
changeWeather(){
this.isHot = !this.isHot
}
},
watch:{
//正常写法
/* isHot:{
immediate:true, //初始化的时候让handler调用一下
deep:true, //深度监视
//handler什么时候调用?当isHot发生改变时
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
} */
//简写
/* isHot(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
} */

}
})
//正常写法
/* vm.$watch('isHot',{
immediate:true,
//handler什么时候调用?当isHot发生改变时
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}) */

vm.$watch('isHot',function(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
})

</script>
</html>

实现效果:

20.Vue监视的简写形式_vue.js_02

 

举报

相关推荐

0 条评论