首页 >  vue >  vue2监听数据

前言

vue2响应式的布局给前端带来了更多的便利,而其中监听这一利器就是核心关键。下面我们来介绍关于监听的用法

1、监听数据

data() {
  return {
    count: 0
  };
},
watch: {
  count(newVal, oldVal) {
    console.log(`count 变化了:${oldVal} -> ${newVal}`)
  }
}

 

2、监听对象

data() {
  return {
    user: {
      name: 'Tom',
      age: 18
    }
  };
},
watch: {
  user: {
    handler(newVal, oldVal) {
      console.log(`user 变化了:${JSON.stringify(oldVal)} -> ${JSON.stringify(newVal)}`)
    },
    deep: true
  },
//或者直接监听user对象某个属性变化
"user.name"(newVal, oldVal) {
    console.log(`用户姓名变化了:${oldVal} -> ${newVal}`);
  //当发生变化,则可以执行对应的逻辑
    this.myMethod();
}, }

 

3、监听数组

data() {
  return {
    user: {
      name: 'Tom',
      age: 18
    }
  };
},
watch: {
  user: {
    handler(newVal, oldVal) {
      console.log(`user 变化了:${JSON.stringify(oldVal)} -> ${JSON.stringify(newVal)}`)
    },
    deep: true
  }
}

 

4、计算计算的属性的变化

computed: {
  fullName() {
    return this.firstName + ' ' + this.lastName;
  }
},
watch: {
  fullName(newVal, oldVal) {
    console.log(`fullName 变化了:${oldVal} -> ${newVal}`)
  }
}

 

选择需要的监听方式,可以更好的完成页面操作