计算属性
写在computed中
1. 写起来像一个方法,用起来像一个属性(本质就是一个属性)
2. 注意点:
- 只要跟计算属性相关的数据发生了改变,计算属性就会重新计算,
不相关的值发生变化,不会重新计算计算属性
- 一定要有返回值
3. 什么时候使用计算属性
-根据已知data中的值,生成一个额外的新值,且新值还要跟着data中的值变化而变化
4. computed里面的计算属性名不能和data中的属性名重名
例:
<div id='app'>
num1:<input type='text' v-model='num1' /> +
num2:<input type='text' v-model='num2' /> =
<span> {{ num3 }} <span>
testNum:<input type='text' v-model='test' />
</div>
const vm = new Vue({
el: '#app',
data: {
num1:0,
num2:0,
testNum:0
},
//计算属性
computed: {
num3(){
return +this.num1 + +this.num2 + +this.test
}
}
})
案例2:单选全选案例
<div id='app'>
<div v-for='item in list'>
<input type='checkbox' v-model='item.isChecked' /> {{item.name}}
</div>
<input type='checkbox' v-model='allChecked' /> 全选
</div>
const vm = new Vue({
el: '#app',
data: {
list: [
{
id: 1,
name: '苹果',
isChecked: true
},
{
id: 2,
name: '草莓',
isChecked: false
},
{
id: 3,
name: '芒果',
isChecked: false
}
]
},
computed: {
//这里只设置了return 相当于computed里的get 没有设置set 所以点击全选无效
//allChecked(){
// return this.list.every(item => item.isChecked)
//}
allChecked: {
set(newValue){
this.list.forEach(item => (item.isChecked = newValue))
},
get(){
return this.list.every(item => item.isChecked)
}
}
}
})
监听器 watch
可以通过watch监听一个属性值的变化,只要值发生了变化,就会调用watch的一些方法
watch是vm的一个配置项
监听的属性按照一个方法的格式来写
watch的基本使用
<div id='app'>
<h1> {{ num }} </h1>
</div>
const vm = new Vue({
el:'#app',
data:{
num:0
},
//监听一个值的变化
watch: {
//第一个参数: 新值
//第二个参数: 旧值
num(newValue,oldValue){
console.log('newValue:',newValue,'oldValue:',oldValue)
}
}
})
watch的应用:验证格式
<div id='app'>
<input type='text' v-model='txt' />
<span v-show='isShow'>格式错误,字符个数应在(3-6)个</span>
</div>
const vm = new Vue({
el:'#app',
data: {
txt:'',
isShow: false
},
watch: {
txt(newValue){
if(/^[0-9a-zA-Z]{3,6}$/.test(newValue)){
this.isShow = false
}else{
this.isShow = true
}
}
}
})
watch的应用:数据持久化
- 监听数据的改变,只要数据改变就调用保存数据的方法
- 需要深度监听
- 保存值可以将对象转化为字符串(存的快 省空间)
watch: {
todoList: {
deep: true,
handle(newVal){
localStorage.setItem('list',JSON.stringify(newVal))
}
}
}
watch的其他用法
<div id='app'>
<h1> {{ obj.age }} </h1>
</div>
const vm = new Vue({
el: '#app',
data: {
num:0,
obj: {
age:10
}
},
watch: {
//监听简单类型
num(newValue){
console.log(newValue)
},
//监听引用类型
obj(newValue){
console.log(newValue)
},
//监听对象里的属性 方式一:
obj: {
//深度监听 监听对象里的属性
deep: true,
//一旦对象里的属性值发生变化,调用handler方法
handler(newValue){
console.log(newValue.age)
}
},
//监听对象里的属性 方式二:
'obj.age'(newValue){
console.log(newValue)
}
}
})
计算属性与监听器的区别使用
watch:监听器
- 监听器监听属性数据发生变化去影响他人
- 自己改变 => 影响他人
computed:计算属性
- 只要 相关属性的数值发生了变化,计算属性会重新计算
- 根据已知的值,得到一个新值
- 别人改变 => 影响自己