计算属性 computed
<span>{{fullName}}</span>
data: {
firstName: '张',
lastName: '三'
},
computed: {
fullName: {
// get有什么作用?当读取fullName时,get就会被调用,且返回值就作为fullName的值。
// get什么时候被调用? 1.初次读取fullName时 2.所依赖的数据发生变化时
get(){
return this.firstName + this.lastName
// return '李四'
},
// set什么时候被调用?当fullName被修改时
set(){
this.firstName = '李'
this.lastName = '四'
}
}
}
计算属性的简写形式:
data: {
firstName: '张',
lastName: '三'
},
computed: {
fullName() { //这里的 fullName 是值,不是函数!!!
return this.firstName + this.lastName //将计算后的值返回给fullName
}
}
监视属性 watch
<span>{{isHot ? '炎热':'寒冷'}}</span>
<button @click="onClick">切换天气</button>
data: {
isHot: true
},
methods: {
onClick(){
this.isHot = !this.isHot
}
},
// 监视属性可以监视data中的值,也可以监视计算属性中的值
watch: {
isHot: {
// immediate为true表示初始化时让handler调用一下
immediate: true,
// 深度监视,一般用于监视多层数据结构的时候用到,比如对象中某个数据的变化
// deep: true,
// handler什么时候调用?当isHot发生改变时,里面可以观察到旧值和新值的变化。
handler(newValue, oldValue){
console.log('被调用了', newValue, oldValue)
}
}
}
监视属性的简写形式:注意在不使用immediate、deep的时候可以使用简写形式
data: {
isHot: true
},
methods: {
onClick(){
this.isHot = !this.isHot
}
},
// 注意在不使用immediate、deep的时候可以使用简写形式
watch: {
isHot(newValue, oldValue) {
console.log('被调用了', newValue, oldValue)
}
}
}
监视属性的完整写法:
vm.$watch('isHot', {
// immediate: true,
// deep: true,
handler(newValue, oldValue){
console.log('被调用了', newValue, oldValue)
}
})
//或者
vm.$watch('isHot', function(){
// immediate: true,
// deep: true,
console.log('被调用了', newValue, oldValue)
})
应用案例:
watch:{
'$route.query.id'(newValue, oldValue){
console.log('变化', newValue, oldValue)
location.reload() // 当路由中参数变化时,刷新当前页面
}
}