一:3种实现姓名案例:
基于插值实现(就是双向绑定)
<div id="root">
姓:<input type="text" v-model="firstname">
名:<input type="text" v-model="lastname">
<br>
<!-- slice(0,3)截取三位,3不包括 -->
姓名:<span>{{firstname.slice(0,3)}}-{{lastname}}</span>
</div>
<script>
new Vue({
el:'#root',
data:{
firstname:"张",
lastname:'三',
}
})
</script>
基于methods实现:
记得调用回调函数有返回值时要加括号
<div id="root">
姓:<input type="text" v-model="firstname">
名:<input type="text" v-model="lastname">
<br>
<!-- slice(0,3)截取三位,3不包括 -->
姓名:<span>{{fullname()}}</span>
</div>
<script>
new Vue({
el:'#root',
data:{
firstname:"张",
lastname:'三',
},
methods:{
fullname(){
return this.firstname+this.lastname
}
}
})
</script>
计算属性实现:要用这个属性不存在,通过已有的属性上去加工计算出来的属性 关键字: computed
写在Vue对象的watch
中,它的值是配置对象——即属性名
当被监听的属性改变时,回调函数自动调用,进行相关操作
监视的属性必须存在,才能进行监视
优点;有缓存,效率高
<div id="root">
姓:<input type="text" v-model="firstname">
名:<input type="text" v-model="lastname">
<br>
<!-- slice(0,3)截取三位,3不包括 -->
姓名:<span>{{fullname}}</span>
</div>
<script>
new Vue({
el:'#root',
data:{
firstname:"张",
lastname:'三',
},
computed:{
fullname:{
//get作用:有人读取就调用get,并且返回值为fullname的值
//get初次读取fullname会被调用,所依赖的数据发生变化时也会被调用
get(){
return this.firstname+this.lastname
},
//当fullname修改时就调用
set(value){
const arr=value.splice('-')
this.firstname=arr[0]
thid.lastname=arr[1]
}
}
}
})
</script>
总结:
计算属性-简写·
computed:{
//简写等于get函数,前面是名字
fullname() {
return this.firstname+this.lastname
}
}
二:监视(天气案例)
<div id="root">
<h2>今天天气很{{info}} </h2>
<button @click="ishost=!ishost">切换</button>
</div>
<script>
new Vue({
el:'#root',
data:{
ishost:true
},
computed:{
info(){
return this.ishost ? '炎热': '冷'
}
},
methods:{
// change(){
// this.ishost=!this.ishost
// }
}
})
</script>
天气案例的监视属性:当监视属性变化时,监视属性自动调用
<div id="root">
<h2>今天天气很{{info}} </h2>
<button @click="change">切换</button>
</div>
<script>
const vm=new Vue({
el:'#root',
data:{
ishost:true
},
computed:{
info(){
return this.ishost ? '炎热': '冷'
}
},
methods:{
change(){
this.ishost=!this.ishost
}
},
//监视
// watch:{
// //当ishost发送改变时调用
// ishost:{
//
// handler(newValue){
// console.log(newvalue)
// }
// }
// }
})
vm.$watch('ishost',{
handler(){
console.log(newvalue)
}
})
监视总结:
3.2深度监视:
大家都知道,Vue项目中对数据的监听,提供了一个很好的钩子watch,watch可以极其方便的监听我们常用数据类型值的变化,但通常当我们想监听一个对象中,某个属性值的变化时,很难达到我们预期的效果。那么如何实现对象属性的深度监听呢
<div id="root">
<h2>今天天气很{{info}} </h2>
<button @click="change">切换</button>
<hr>
<h2>a:{{numbers.a}}</h2>
<button @click="numbers.a++">点我+1</button>
<h2>b:{{numbers.b}}</h2>
<button @click="numbers.b++">点我+1</button>
</div>
<script>
const vm=new Vue({
el:'#root',
data:{
ishost:true,
numbers:{
a:1,
b:2
}
},
computed:{
info(){
return this.ishost ? '炎热': '冷'
}
},
methods:{
change(){
this.ishost=!this.ishost
},
},
//监视
watch:{
//当ishost发送改变时调用
ishost:{
handler(newValue){
console.log(newvalue)
}
},
//监视多级结构中某个属性变化
'numbers.a':{
handler() {
console.log('change')
}
},
numbers: {
//监视多级结构所有属性变化
deep:true,
handler(){
console.log('numbers所有属性改变')
}
}
}
})
总结:
监视的简写模式:
//简写
ishost(newvalue,oldvalue){
console.log(newvalue,oldvalue)
},
四:姓名案例与天气案例对比