Vue学习-计算属性和侦听器
一、 计算属性(computed)
1、计算属性的定义和原理
2、基础例子
计算属性有两种写法,当需要修改计算属性的值时用完整写法(即需要set方法),否则用简写形式。
(1)完整写法
<body>
<div id="app">
<input type="text" v-model="a"><br>
<input type="text" v-model="b"><br>
<h1 v-text="full"></h1><br>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var vm=new Vue({
el:"#app",
data(){
return{
msg:"Hello World!",
a:"李",
b:"明"
}
},
computed:{
/*get有什么作用?当有人读取full时,get就会被调用,且返回值就作为full的值
get什么时候调用?
1.初次读取full时。
2.所依赖的数据发生变化时。
*/
full:{
get(){
console.log("full get被调用了")
return this.a+"-"+this.b
},
set(value){
console.log("full set被调用了")
var str=value.split("-")
this.a=str[0]
this.b=str[1]
}
}
}
})
</script>
</body>
(2)简写形式
computed:{
//简写,只有get方法
full(){
console.log(' full get被调用了')
return this.firstName + '-' + this.lastName
}
}
二、 侦听器(watch)
1、侦听器
2、基础例子
(1)完整写法
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
</div>
const vm = new Vue({
el:'#root',
data:{
isHot:true,
},
computed:{
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
//new Vue时传入watch配置
/* watch:{
isHot:{
immediate:true, //初始化时让handler调用一下
//handler什么时候调用?当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}
} */
})
//通过vm.$watch监视
vm.$watch('isHot',{
immediate:true, //初始化时让handler调用一下
//handler什么时候调用?当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
})
(2)简写形式
//new Vue时传入watch配置
//简写
isHot(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue,this)
}
//通过vm.$watch监视
//简写
vm.$watch('isHot',(newValue,oldValue)=>{
console.log('isHot被修改了',newValue,oldValue,this)
}) */